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.

有帮助吗?

解决方案

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

其他提示

You CAN do this very easily...

You can wrap the MERGE statement within a INSERT INTO FROM:
http://technet.microsoft.com/en-us/library/bb510625.aspx#sectionToggle2

-OR-

You can do it directly within the merge statement:

Quick example:

WHEN NOT MATCHED THEN
    DELETE
OUTPUT Deleted.* INTO dbo.MyTable;

This will insert the non-matches into your existing destination table. You can use te Updated, Inserted, Deleted v-tables to direct data other places.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top