Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete from source using MERGE command in SQL Server 2008?

I am currently using the below merge code to migrate date from source to target. I have a new requirement to extend the below code to delete the record from source once an update/insert is performed on the target. Is this possible using merge(all the examples i see on the net had performing del/insert/update in the target not on the source)

    MERGE Target1 AS T USING Source1 AS S ON (T.EmployeeID = S.EmployeeID)  WHEN NOT MATCHED BY TARGET AND S.EmployeeName LIKE 'S%'      THEN INSERT(EmployeeID, EmployeeName) VALUES(S.EmployeeID, S.EmployeeName) WHEN MATCHED      THEN UPDATE SET T.EmployeeName = S.EmployeeName WHEN NOT MATCHED BY SOURCE AND T.EmployeeName LIKE 'S%'     THEN DELETE  ; 
like image 808
nfa379 Avatar asked Sep 07 '11 09:09

nfa379


People also ask

Can we use Delete in MERGE statement?

Instead of writing a subquery in the WHERE clause, you can use the MERGE statement to join rows from a source tables and a target table, and then delete from the target the rows that match the join condition.

What is purpose of MERGE in SQL Server 2008?

Starting with SQL Server 2008, you can use a MERGE statement to modify data in a target table based on data in a source table. The statement joins the target to the source by using a column common to both tables, such as a primary key.

How do I MERGE statements in SQL Server?

First, you specify the target table and the source table in the MERGE clause. Second, the merge_condition determines how the rows from the source table are matched to the rows from the target table. It is similar to the join condition in the join clause.

How does MERGE statement work in SQL?

The MERGE statement basically works as separate INSERT, UPDATE, and DELETE statements all within the same statement. You specify a "Source" record set and a "Target" table and the JOIN condition between the two.


1 Answers

You can use the output clause to capture the modified/inserted rows to a table variable and use that with a delete statement after the merge.

DECLARE @T TABLE(EmployeeID INT);  MERGE Target1 AS T USING Source1 AS S ON (T.EmployeeID = S.EmployeeID)  WHEN NOT MATCHED BY TARGET AND S.EmployeeName LIKE 'S%'      THEN INSERT(EmployeeID, EmployeeName) VALUES(S.EmployeeID, S.EmployeeName) WHEN MATCHED      THEN UPDATE SET T.EmployeeName = S.EmployeeName WHEN NOT MATCHED BY SOURCE AND T.EmployeeName LIKE 'S%'     THEN DELETE   OUTPUT S.EmployeeID INTO @T;  DELETE Source1 WHERE EmployeeID in (SELECT EmployeeID                      FROM @T); 
like image 62
Mikael Eriksson Avatar answered Sep 26 '22 06:09

Mikael Eriksson