Use of Merge in SQL Server, sqlmerge

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.