Reputation: 116950
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:
Status = 1
Status = 1
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?
Upvotes: 1
Views: 77
Reputation: 15849
You want the "NOT MATCHED BY SOURCE" clause.
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 Status = 1
WHEN NOT MATCHED THEN
INSERT (ColA, ColB, Status) VALUES(Source.ColA, Source.ColB, 1)
WHEN NOT MATCHED BY SOURCE THEN
UPDATE SET Status = 0
;
Upvotes: 1