With the Merge statement we can merge data from a souce table into a target table.
Synatx
- MERGE INTO <Target Table > AS TRG
- USING <Souce Table> As SRC
- ON <Merge Conidtion>
- WHEN MATCHED [AND Condition]
- THEN <Action>
- WHEN NOT MATCHED [BY TARGET ] [AND Condition]
- THEN <Action>
- WHEN NOT MATCHED BY SOURCE [AND CONIDTION]
- THEN <Action.
USING <Source Table>: This clause defines the source table for the opearation. In Source Table we can use a table, CTE, Dervied Table, some other database table, OPENROWSET or XQUERY.
ON<Merge Condition>: This is just like an ON clause like in joins. This statement defines both the souce table and the target table as Matched or NotMatched.
WHEN MATCHED [AND Condition] THEN <ACTION>: This clause defines the When of both the Souce Table and the Target Table matched based on the key. Here [AND Condition] is optional. Here we can perform two actions, either update or delete on the target table.
WHEN NOT MATCHED [BY TARGET ] [AND Condition] THEN <ACTION>: This clause defines the When Target Table that is matched based on key. Here the [AND Condition] is optional. Here we can perform only the one action, Insert.
WHEN NOT MATCHED BY SOURCE [AND Condition] THEN <ACTION>: This clause defines the When Source Table that is matched based on key. Here the [AND Condition] is optional. Here we can perform one of two actions, either Update or Delete on the target table.
Realistic Scenario Using Merge Statement
- --Created Stored Procedure With Old Way
- create procedure InsUpStudent
- (@Name varchar(20),@Marks int)
- as
- begin
- if exists(select * from Student where Name=@Name)
- begin
- update Student set Marks=@Marks where Name=@Name
- end
- else
- begin
- insert into Student(Name,Marks) values(@Name,@Marks)
- end
- end
- --Test Some Sample data with above procedure.
- exec InsUpStudent 'Rakesh',500 --Here record need to insert into Student table beacuse of Rakesh does not exists.
- exec InsUpStudent 'Rakesh',600 --Here record need to update into Student table beacuse of Rakesh already exists.

shainul rizviPosted Apr 10, 2016, 2:36 AM
nice article
Sr KarthigaPosted Mar 8, 2016, 11:25 AM
good one
Sr KarthigaPosted Mar 8, 2016, 11:25 AM
nice explanation
Santhakumar MunuswamyPosted Feb 18, 2015, 9:23 AM
Thanks for very nice article
Shaili DashoraPosted Feb 18, 2015, 7:11 AM
Thank u all..
Khargesh RajputPosted Feb 17, 2015, 6:30 AM
nice article
Harpreet SinghPosted Feb 17, 2015, 2:10 AM
very nice article.
Shaili DashoraPosted Feb 17, 2015, 1:52 AM
Thank you..
Sourabh SomaniPosted Feb 16, 2015, 10:18 PM
Sumit Jolly yeah realy. it is very convenient. :)
Sourabh SomaniPosted Feb 16, 2015, 10:16 PM
Shaili Dashora Best one article... and very good explanation
Guest UserPosted Feb 16, 2015, 9:31 PM
I often use merge as its very convenient.
Guest UserPosted Feb 16, 2015, 9:31 PM
Hi good one! nice explanation.