Merge Statement in SQL Server(TSQL)

 

With the Merge Statement, we can run INSERT, UPDATE, and DELETE commands at one time to synchronize two tables of the same structure.

First, let’s create source and target tables with the following script, and add a few records to these tables.

As you can see in the Script, some of the records in the two tables are different. We will synchronize the records in these two tables using the MERGE statement.

We then sync the source and target tables with the help of the following script.

After “WHEN MATCHED THEN“, if the records match, we run the update statement.

After “WHEN NOT MATCHED BY TARGET THEN“, we perform the insert operation if the record in the source table is not in the target table.

After “WHEN NOT MATCHED BY SOURCE THEN“, we delete a record that is in the target table from the target table if it is not in the source table.

With OUTPUT statement, we produce the changes made as output.

dbtut
Author: dbtut

We are a team with over 10 years of database management and BI experience. Our Expertises: Oracle, SQL Server, PostgreSQL, MySQL, MongoDB, Elasticsearch, Kibana, Grafana.

Leave a Reply

Your email address will not be published. Required fields are marked *