Use of Merge in SQL Server, sqlmerge
Many people know that ORACLE has the Merge keyword. In fact, SQL Server also supports Merge from the beginning of version 2008.
You can also perform Update, Insert, and Delete operations in the same SQL statement as ORACLE.
The following is a simple example,
Number of rows:
IF OBJECT_ID ('testa ', 'U') is not nullddrop TABLE testagif OBJECT_ID ('testb', 'U') is not nullddrop TABLE TestBGOCREATE TABLE TestA (id int, title NVARCHAR (200) gocreate table TestB (id int, Title NVARCHAR (200) goinsert into TestA (ID, Title) VALUES (1, N 'A'), (2, N 'B'), (3, N 'C'), (4, N 'D'), (5, N 'E') GOINSERT INTO TestB (ID, Title) VALUES (1, N '1'), (3, N '3'), (5, N '5'), (7, N '7'), (9, N '9') GO
Now, we need to use TestB to Update TestA, Update with the same ID, and Insert with different IDs.
The common practice is to take two steps:
UPDATE aSET a.Title = b.TitleFROM TestA aINNER JOIN TestB b ON a.ID = b.ID;INSERT INTO TestA(ID,Title)SELECT a.ID,a.TitleFROM TestB aWHERE NOT EXISTS(SELECT * FROM TestA WHERE ID = a.ID);
With Merge, you can do it with one sentence, and the efficiency is very high:
MERGE INTO TestA AS aUSING TestB AS bON (a.ID = b.ID)WHEN MATCHEDTHEN UPDATE SET a.Title = b.TitleWHEN NOT MATCHED BY TARGETTHEN INSERT(ID,Title) VALUES(b.ID,b.Title);
For more use of Merge, please refer to MSDN: Exam 1 and Exam 2.