Articles → SQL SERVER → Merge Command In SQL Server
Merge Command In SQL Server
Source And Target
- Table 1 and Table 2 contain the same records
- Table 1 and Table 2 contain distinct records
Syntax
-- Syntax
MERGE Table1 T using Table2 S ON S.column_name = T.column_name WHEN NOT MATCHED THEN INSERT(
TargetColumn1, TargetColumn2,...
)
VALUES
(
SourceColumn1, SourceColumn2,...
) WHEN MATCHED THEN
UPDATE
SET
T.Column1 = S.Column1;
Sample
- OfficeSource
- OfficeTarget
-- Query
MERGE OfficeTarget T using OfficeSource S ON S.office_id = T.office_id WHEN NOT MATCHED THEN INSERT(office_location)
VALUES
(office_location) WHEN MATCHED THEN
UPDATE
SET
T.office_location = S.office_location;