MERGE
will, unfortunately, not let you apply multiple actions to one condition, or let you operate multiple times on one row.
So, what I do is use an INSERT INTO
wrapping up the MERGE
:
INSERT INTO DimTable
SELECT ID, Name, StartDate, null as EndDate
FROM
(
MERGE DimTable AS tgt
USING StageTable AS src
ON tgt.id = src.id AND tgt.enddate IS NULL
WHEN MATCHED THEN
UPDATE SET tgt.enddate = src.startdate
WHEN NOT MATCHED THEN
INSERT INTO (ID, Name, StartDate)
VALUES (src.id, src.name, src.startdate)
OUTPUT $action as Action, src.ID, src.Name, src.StartDate
) a
WHERE
a.Action = 'UPDATE'
The key there is the OUTPUT
clause which will actually redirect those rows so you know exactly what happened to them. A brilliant feature, really.