SQL DB Help is a technical blog dedicated to Microsoft SQL Server development and administration. Explore expert tips, practical solutions, and best practices for managing SQL databases, performance tuning, T-SQL scripting, and more. Ideal for DBAs, developers, and IT professionals seeking reliable SQL Server guidance.
Sunday, May 31, 2020
How to write a merge statement in SQL Server
How to write a merge statement in SQL Server
SQL Server provides the MERGE statement that allows you to perform three actions at the same time. If you use the INSERT, UPDATE, and DELETE statements individually, you have to construct three separate statements to update the data to the target table with the matching rows from the source table.
The following shows the syntax of the MERGE statement:
MERGE USING
ON -- join condition base on matched column by foreign key relation or primary key and unique key
WHEN MATCHED --When records are matched, update the records if there is any change
THEN
WHEN NOT MATCHED --When no records are matched, insert the incoming records from source table to target table
THEN
WHEN NOT MATCHED BY SOURCE -- delete from target when record not matched with source table **
THEN DELETE
OUTPUT $action, --$action specifies a column of type nvarchar(10) in the OUTPUT clause that returns
[], --list of deleted column separated by comma
[], --list of inserted column separated by comma
The statement specifies the target table and the source table in the MERGE clause.
The merge_condition determines how the rows from the source table are matched to the rows from the target table. It is similar to the join condition in the join clause.
The merge_condition results in three states: MATCHED, NOT MATCHED, and NOT MATCHED BY SOURCE.