USING sourceTable - source of data (can be table or view or table valued function)
ON ... - join condition between targetTable and sourceTable.
WHEN MATCHED - actions to take when a match is found
AND (targetTable.PKID > 100) - additional condition(s) that must be satisfied in order for the action to be taken
Comments:
If a specific action is not needed then omit the condition e.g. removing WHEN NOT MATCHED THEN INSERT will prevent records from being inserted
Merge statement requires a terminating semicolon.
Restrictions:
WHEN MATCHED does not allow INSERT action
UPDATE action can update a row only once. This implies that the join condition must produce unique matches.
Merge Using CTE Source
WITH SourceTableCTE AS(SELECT*FROM SourceTable
)MERGE
TargetTable AS target
USING SourceTableCTE AS source
ON(target.PKID = source.PKID)WHENMATCHEDTHENUPDATESET target.ColumnA = source.ColumnA
WHENNOTMATCHEDTHENINSERT(ColumnA)VALUES(Source.ColumnA);
Now, Suppose we want to synchoronize the dbo.Product Target Table with the dbo.ProductNew table. Here is the criterion for this task:
Product that exist in both the dbo.ProductNew source table and the dbo.Product target table are updated in the dbo.Product target table with new new Products.
Any product in the dbo.ProductNew source table that do not exist in the dob.Product target table are inserted into the dbo.Product target table.
Any Product in the dbo.Product target table that do not exist in the dbo.ProductNew source table must be deleted from the dbo.Product target table.
Here is the MERGE statement to perform this task.
MERGE dbo.Product AS SourceTbl
USING dbo.ProductNew AS TargetTbl ON(SourceTbl.ProductID = TargetTbl.ProductID)WHENMATCHEDAND SourceTbl.ProductName <> TargetTbl.ProductName
OR SourceTbl.Price <> TargetTbl.Price
THENUPDATESET SourceTbl.ProductName = TargetTbl.ProductName,
SourceTbl.Price = TargetTbl.Price
WHENNOTMATCHEDTHENINSERT(ProductID, ProductName, Price)VALUES(TargetTbl.ProductID, TargetTbl.ProductName, TargetTbl.Price)WHENNOTMATCHEDBY SOURCE
THENDELETE
OUTPUT $action, INSERTED.*, DELETED.*;
Note:Semicolon must be present in the end of MERGE statement.
(opens new window)
Merge using EXCEPT
Use EXCEPT to prevent updates to unchanged records
MERGE TargetTable targ
USING SourceTable AS src
ON src.id = targ.id
WHENMATCHEDANDEXISTS(SELECT src.field
EXCEPTSELECT targ.field
)THENUPDATESET field = src.field
WHENNOTMATCHEDBY TARGET
THENINSERT(
id
,field
)VALUES(
src.id
,src.field
)WHENNOTMATCHEDBY SOURCE
THENDELETE;
Performs insert, update, or delete operations on a target table based on the results of a join with a source table. For example, you can synchronize two tables by inserting, updating, or deleting rows in one table based on differences found in the other table.