Merge when matched and not matched


The MERGE command in MS SQL is a combination of INSERT, UPDATE, and DELETE in one statement. It allows you to perform these operations on a table, based on the results of a join with a source table. The basic syntax for a MERGE statement is:

MERGE target_table USING source_table
ON merge_condition
WHEN MATCHED THEN update_statement
WHEN NOT MATCHED THEN insert_statement
WHEN MATCHED THEN delete_statement;

MERGE with UPDATE and INSERT:

Let's consider two tables, Employee (target table) and Employee_Updates (source table). The Employee table contains the current employee data, and the Employee_Updates table contains updated employee data

MERGE Employee AS TARGET
USING Employee_Updates AS SOURCE
ON (TARGET.EmployeeID = SOURCE.EmployeeID)
WHEN MATCHED THEN
UPDATE SET TARGET.EmployeeName = SOURCE.EmployeeName, TARGET.EmployeeSalary = SOURCE.EmployeeSalary
WHEN NOT MATCHED BY TARGET THEN
INSERT (EmployeeID, EmployeeName, EmployeeSalary) VALUES (SOURCE.EmployeeID, SOURCE.EmployeeName, SOURCE.EmployeeSalary);

The above command will update the records in the Employee table with the respective records from the Employee_Updates table where the EmployeeIDs match. If there is a record in the Employee_Updates table that does not exist in the Employee table, then it would be inserted into the Employee table.

MERGE with DELETE:

MERGE Employee AS TARGET
USING Employee_Deletes AS SOURCE
ON (TARGET.EmployeeID = SOURCE.EmployeeID)
WHEN MATCHED THEN
DELETE;

The above command will delete the records from the Employee table that have a match in the Employee_Deletes table.

 


No files yet, migration hasn't completed yet!