I have two tables:
Table 1:
ID ColA ColB Status
Table 2:
ColA ColB
I am trying to MERGE records from Table 2 into Table 1 in a way that:
- For every row in Table 2 present in Table 1, I set
Status = 1 - For every row in Table 2 NOT present in Table 1, I insert the row into Table 1 and set
Status = 1 - For every row in Table 1 NOT present in Table 2, set
Status = 0
Is it possible to do this in one statement? Currently, I am able to achieve 1 and 2 but am not sure how to get the third one as well:
MERGE INTO dbo.Table1 WITH(HOLDLOCK) AS Target
USING dbo.Table2 AS Source
ON Target.ColA = Source.ColA AND Target.ColB = Source.ColB
WHEN MATCHED THEN
UPDATE SET Target.Status = 1
WHEN NOT MATCHED THEN
INSERT (ColA, ColB, Status) VALUES(Source.ColA, Source.ColB, 1);
Any suggestions on how to achieve 3 in the same statement?
You want the “NOT MATCHED BY SOURCE” clause.