8

我想创建一个合并,它将比较两个表并将不匹配的值插入到另一个第三个表或表变量中,如下所示:

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())

可以这样做还是有其他方法?

4

2 回答 2

13

不能这样做。MERGE仅在两个表上运行 - 源和目标。

根据您的要求,您需要例如使用 CTE(通用表表达式)来查找不匹配的行 - 并将这些行插入到第三个表中。

就像是:

;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
于 2012-02-22T15:46:35.300 回答
11

你可以很容易地做到这一点......

您可以将 MERGE 语句包装在 INSERT INTO FROM 中:
http ://technet.microsoft.com/en-us/library/bb510625.aspx#sectionToggle2

-或者-

您可以直接在合并语句中执行此操作:

快速示例:

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

这会将不匹配项插入到您现有的目标表中。您可以使用已更新、已插入、已删除的 v 表将数据定向到其他位置。

于 2012-12-24T20:05:16.490 回答