What is Merge command?
Merge provides an efficient way to perform multiple DML operations. Using the MERGE statement we can include the logic of such data modifications in one statement that even checks when the data is matched, then just update it, and when unmatched, then insert it.
Step by step explanation of merge statement:
Step 1: Create a target table.
- create table Book
- (
- BID int identity(1,1)primary key,
- Title varchar(50),
- Quantity int,
- Price int
- )
Step 2: Create a source table.
- create table BookOrder
- (
- OID int identity(1,1)primary key,
- Title varchar(50),
- Quantity int,
- Price int
- )
- insert Book values('ASP.Net 4.0',5,890)
- insert Book values('C#.Net 4.0',8,990)
- insert Book values('ADO.Net 4.0',7,400)
- insert Book values('VB.Net 4.0',12,720)
- insert Book values('Silverlight',4,880)
- insert into BookOrder values('C#.Net 4.0',4,990)
- insert into BookOrder values('MVC4',4,1800)
- insert into BookOrder values('ADO.Net 4.0',4,400)
- insert into BookOrder values('JQuery',4,640)
- insert into BookOrder values('WCF',3,740)
Example 1: When Matched: Update tagrate table from source data
- merge Book b using BookOrder o
- on b.Title=o.Title
- when matched then
- update
- set b.Quantity=b.Quantity+o.Quantity;
- Truncate table BookOrder
Example 2: When not Matched: Update tagrate table from source data if it matches otherwise insert new row from source table,
- merge Book b using BookOrder o
- on b.Title=o.Title
- when matched then
- update
- set b.Quantity=b.Quantity+o.Quantity
- when not matched by target then
- insert (Title,Quantity,Price) values(o.Title,o.Quantity,o.Price);
- Truncate table BookOrder
Example 3: When not Matched: Update tagrate table from source data if it matches otherwise delete row from Targate table,
- merge Book b using BookOrder o
- on b.Title=o.Title
- when matched then
- update
- set b.Quantity=b.Quantity+o.Quantity
- when not matched by source then
- delete;
- Truncate table BookOrder


Bhuvan PandeyPosted Jul 21, 2016, 4:15 AM EDT
Thanx every one to follow my article.
SubashPosted Jul 20, 2016, 9:43 PM EDT
Good Very Nice
Nigel FernandesPosted Jul 20, 2016, 5:44 PM EDT
Useful
Raja TPosted Jul 20, 2016, 4:02 PM EDT
Nice....
Mahesh ChandTOP 10Posted Jul 20, 2016, 1:15 PM EDT
Is this just SQL Server 2008 or any SQL? Or all SQL Server versions? Please clarify in the article. Most of the SQL commands usually applies to most of the common databases.
RakeshPosted Jul 20, 2016, 8:35 AM EDT
Good share
Lalit RaghavPosted Jul 20, 2016, 2:27 AM EDT
Nice article
kalu singh raoPosted Jul 19, 2016, 9:33 PM EDT
Good explanations