January 21, 2009 at 5:18 pm
Hi i have 2 tables: tempo1 and tempo2, i need to move data from tempo1 to tempo2, if a row with some id already exist then it must be update, else it must be inserted, i once saw a trigger that did this by using try catch or a @@ variable, yet i cannot recall or find out how was this done, has anyone done or seen this before?
January 21, 2009 at 5:33 pm
you don't even need to check, really
you simply do two steps in the trigger
you update first, and if it exists, it gets updated. if it didn't exist, nothing gets touched.
then you insert by left outer joining where the common key in the second table is NULL.
--ie
CREATE TRIGGER TR_WHATEVER
FOR INSERT,UPDATE
AS
UPDATE TABLE2
SET TABLE2.Value = INSERTED.Value
FROM INSERTED
WHERE INSERTED.ID = TABLE2.ID
--then
INSERT INTO TABLE2
SELECT INSERTED.* FROM INSERTED
LEFT OUTER JOIN TABLE2 ON INSERTED.ID = TABLE2.ID
WHERE TABLE2.ID IS NULL
Lowell
January 22, 2009 at 8:23 am
thanks a lot mate, that looks even better 😀
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply