I have two identical SQL Server tables (SOURCE and DESTINATION) with lots a columns in each. I want to insert into table DESTINATION rows from table SOURCE that do not already exist in table DESTINATION. I define equality between the two rows if all columns match except for the timestamp, a count column, and the integer primary key. So I want to insert into DESTINATION all rows in SOURCE that dont already exist in DESTINATIONignoring count, timestamp, and the primary key columns.
How do I do this?
Thanks for all the contributions! I chose to use the Merge command since it is structured to allow for updates and inserts in one statement 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 first I called the tables AAA and BBB. I edited and changed the names of AAA to SOURCE AND BBB to DESTINATION for clarity
using
Selectstatement for this purpose since Sql Server 2008 is obsolete instead ofSelectYou can useMergestatement :ref:
http://technet.microsoft.com/en-us/library/bb510625.aspx
http://weblogs.sqlteam.com/peterl/archive/2007/09/20/Example-of-MERGE-in-SQL-Server-2008.aspx