SQL Server 2008 and newer have a MERGE statement that does just that.
For more information, see the Email Documents for MSDN at MERGE .
Basically, you need four things:
- a source (table or view or built-in SELECT statement)
- a target
- a JOIN condition that binds two
- for cases where there is MATCH (strings exist both in the source and in the target), NOT MATCHED (when the string does not yet exist in the target), etc.
So, you basically define something like:
MERGE (targettable) AS t USING (sourcetable) AS s ON (JOIN condition between s and t) WHEN MATCHED THEN UPDATE SET t.Col1 = s.Col1, t.Col2 = s.Col2 (etc.) WHEN NOT MATCHED THEN INSERT(Col1, Col2, ..., ColN) VALUES(s.Col1, s.Col2, ......, s.ColN)
This is done as a single statement and is highly optimized by SQL Server.
source share