Use of merge in SQL Server

Source: Internet
Author: User

Many people know that there is a merge key in Oracle, and SQL Server actually supports merge from version 2008.

The update, Insert, and delete operations can also be done in a SQL sentence in the same way as Oracle.

Here is a simple example of a direct code,

Number of preparations:

IF object_id (' TestA ', ' u ') is not nulldrop table testagoif object_id (' Testb ', ' u ') are not nulldrop table Testbgocreate table TestA (ID int,title NVARCHAR ()) Gocreate TABLE testb (id int,title NVARCHAR ()) 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 ' one '), (3,n ' three '), (5,n ' V '), (7,n ' seven ') , (9,n ' IX ') GO
Now the need is to use TESTB to update testa,id the same Update,id different insert

The normal method is two steps away:

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.titlef ROM Testb Awhere not EXISTS (SELECT * from TestA WHERE ID = a.id);
With the merge, it can be done in one sentence, and it's still high efficiency:

MERGE into TestA as ausing Testb as BON (a.id = b.id) when Matchedthen UPDATE SET a.title = B.titlewhen not matched by Targ Etthen INSERT (id,title) VALUES (b.id,b.title);


For more use of the merge, or please refer to MSDN: 1, references 2

Use of merge in SQL Server

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.