MERGE
per joined row: WHEN MATCHED (update/delete), WHEN NOT MATCHED BY TARGET (insert), WHEN NOT MATCHED BY SOURCE (update/delete)
What changes
- Input
- target table and a source table expression joined ON a condition
- Output or change
- inserts, updates and deletes on the target; optional OUTPUT with $action
Syntax at a glance
[ WITH <common_table_expression> [,...n] ] MERGE [ TOP ( expression ) [ PERCENT ] ] [ INTO ] <target_table> [ WITH ( <merge_hint> ) ] [ [ AS ] table_alias ] USING <table_source> [ [ AS ] table_alias ] ON <merge_search_condition> [ WHEN MATCHED [ AND <clause_search_condition> ] THEN <merge_matched> ] [ ...n ] [ WHEN NOT MATCHED [ BY TARGET ] [ AND <clause_search_condition> ] THEN <merge_not_matched> ] [ WHEN NOT ...
Work example
A bounded source set must update matching target keys and insert new keys in one statement.
Run the sample only against its table variable. Prove the source has one row per key and review concurrency behavior before choosing MERGE for a real workload.
Check your work MERGE. Id 1 has 15 points and Id 2 has 20. Each source key changes one target row at most.
Practice SQL
Open in SQL FlowDECLARE @Target TABLE (Id int PRIMARY KEY, Points int);
INSERT @Target VALUES (1, 12);
MERGE @Target AS target
USING (VALUES (1, 15), (2, 20)) AS source(Id, Points)
ON target.Id = source.Id
WHEN MATCHED THEN UPDATE SET Points = source.Points
WHEN NOT MATCHED THEN INSERT (Id, Points) VALUES (source.Id, source.Points);
SELECT Id, Points FROM @Target ORDER BY Id;
Open Microsoft Learn for full syntax, permissions, and details for your version.