Articles → SQL SERVER → Merge Command In SQL Server

Merge Command In SQL Server








Source And Target




  1. Table 1 and Table 2 contain the same records
  2. 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






  1. OfficeSource
  2. OfficeTarget




Picture showing the output of the merge command where value does not exists




-- 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;




Picture showing the data merged between the 2 tables




Picture showing the output of the merge command when both tables contains different records on the same id




Picture showing the data merged between the 2 tables




Picture showing the output of the merge command when one table contains more records than other




Picture showing the data merged between the 2 tables



Posted By  -  Karan Gupta
 
Posted On  -  Sunday, January 31, 2016

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250