SQL Merge with inserting into the other table

iLemming picture iLemming · Feb 22, 2012 · Viewed 24.5k times · Source

I want to create a merge that will compare two tables and insert not matched values into another third table or table variable something like this:

MERGE Assets AS target
USING (@id, @name)FROM Sales AS source (id, name) ON (target.id = SOURCE.id)
WHEN MATCHED THEN 
    UPDATE SET target.Status = @status, target.DateModified = SYSUTCDATETIME()
WHEN NOT MATCHED THEN 
    INSERT INTO @tableVar (id, name, status, dateModified)  
    VALUES (@id, @name, @status, SYSUTCDATETIME())

Would you guys help me to transform it using some other constructs.

Answer

marc_s picture marc_s · Feb 22, 2012

You just cannot do this. MERGE operates on two tables only - source and target.

For your requirement, you need to e.g. use a CTE (Common Table Expression) to find the rows that don't match - and insert those into the third table.

Something like:

;WITH NonMatchedData AS
(
   -- adapt this as needed - just determine which rows match your criteria,
   -- and make sure to return all the columns necessary for the subsequent INSERT
   SELECT (columns)
   FROM dbo.SourceTable
   WHERE ID NOT IN (SELECT DISTINCT ID FROM dbo.TargetTable)
)
INSERT INTO dbo.ThirdTable(Col1, Col2, ....., ColN)
  SELECT Col1, Col2, ....., ColN
  FROM NonMatchedData