Category: SQL Server
view more software Tips and Tricks
Updated: 06/24/2014 12:06 PM
Author: Shiju Mathews
Starting with SQL Server 2008, you can use a MERGE statement to modify data in a target table based on data in a source table. The statement joins the target to the source by using a column common to both tables, such as a primary key. You can then insert, modify, or delete data from the target table—all in one statement—according to how the rows match up as a result of the join. The MERGE statement supports several clauses that facilitate the different types of data modifications.
To understand this create 2 tables.
Fill table with some random values.
Now use the merge
As you can see, the statement begins with the MERGE keyword, followed by the name of the target table.
The next line in the statement is the USING clause, which is made up of the USING keyword, followed by the source table.
After specified the target and source tables as well as the join condition, I added a WHEN MATCHED clause. The clause includes the WHEN MATCHED keywords, followed by the THEN keyword, next the UPDATE or Insert keyword.
Now validate the table data.