I have two identical SQL Server tables ( SOURCE
and DESTINATION
) with many columns in each. I want to insert into the DESTINATION
table rows from the SOURCE
table that do not yet exist in the DESTINATION
table. I define equality between two rows if all columns are the same except for the timestamp, count column, and integer primary key. So I want to insert in DESTINATION
all the rows in SOURCE
that no longer exist in DESTINATION
, ignoring the count, timestamp and primary key columns.
How to do it?
Thanks for all the contributions! I decided to use the Merge command because it is structured to update and paste in one of the statements, and I needed to do the update separately.
this is the code that worked:
Merge into DESTINATION as D using SOURCE as S on ( D.Col1 = S.Col1 and D.Col2 = S.Col2 and D.Col3 = S.Col3 ) WHEN MATCHED THEN UPDATE SET D.Count = S.Count WHEN NOT MATCHED THEN INSERT (Col1, Col2, Col3, Count, timestamp) VALUES (S.Col1, S.Col2, S.Col3, S.Count, S.timestamp);
Note: when I wrote this question, I first called the AAA
and BBB
tables. I edited and changed the names AAA
to SOURCE
and BBB
to DESTINATION
for clarity
source share