Legend
Legend

Reputation: 116950

Upsert with modifications to excluded rows?

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:

  1. For every row in Table 2 present in Table 1, I set Status = 1
  2. For every row in Table 2 NOT present in Table 1, I insert the row into Table 1 and set Status = 1
  3. 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?

Upvotes: 1

Views: 77

Answers (1)

Rob Farley
Rob Farley

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

Related Questions