Trigger to update existing data or insert if data does not exist (multi-line caliper)
I have two tables, both tables contain similar columns "username", "date" and "time". One table (table 2) is essentially a summation of the "time" column for a date, where table1 can have multiple "times" for each date.
I have no control over any of the statements used to insert data into table1, so I thought the best way to do it would be to use a trigger on table1 that inserts into or updates table2 depending on whether a row exists for the date (s) ... To do this, something similar to the following would be fine:
IF NOT EXISTS(SELECT * FROM table2 WHERE date = @date/*date from inserted*/)
--insert into table 2 here
ELSE
--update table 2 here
However, the problem is that I also need support for multiple rows on the trigger, which will cause the previous one to fail IF
. One idea would be to loop over each insert line, but from what I've read, this will have a big performance impact that I want to avoid (this is the last resort if there is no better way).
So, is there a way to do what I need without using some kind of loop?
An example of an insert I'll be using:
INSERT INTO table2 (username, date, time)
SELECT i.username, i.date, SUM(w.time) FROM inserted AS i
JOIN (SELECT username, date, time FROM table1/*table with trigger*/) AS w
ON w.date = i.date AND w.username = i.username
GROUP BY i.username, i.date
Thanks in advance for any advice!
Note. I'm new to SQL, so sorry if I missed something or made obvious mistakes!
EDIT (solution):
A working solution (thanks to @Ronak Vyas answer) looks like this:
MERGE table2 AS m
USING (SELECT i.username, i.date, SUM(w.time) FROM inserted AS i
JOIN (SELECT username, date, time FROM table1/*table with trigger*/) AS w
ON w.date = i.date AND w.username = i.username
GROUP BY i.username, i.date) AS s
ON m.date = s.date AND m.username = s.username
WHEN MATCHED THEN UPDATE SET m.duration = s.duration
WHEN NOT MATCHED THEN
INSERT (username, date, time)
VALUES (s.username, s.date, s.time)
Thank you so much!
source to share