我有一个MERGE
查询来更新数据。如果没有匹配,我将源记录插入到获取输出到临时表。
是否可以将匹配的记录提供给临时表?基本上为了避免在进一步处理中重复数据,我需要有匹配记录的副本。
这是我的MERGE
命令:
MERGE Product.ProductHeaderRepository AS t
USING (SELECT GETDATE() as d, c1, c2, c3,
Name FROM Supplier.ProductHeaderImport
WHERE (BatchID = @BatchID) ) AS s
ON dbo.GetProductHeaderId(s.c1,S.c2,S.c3) <0
WHEN NOT MATCHED BY TARGET THEN
INSERT (Name, c1,c2,c3) VALUES (Name, c2,c2,c3)
OUTPUT INSERTED.iD, s.c1, s.c2, s.c3 INTO @TmpTable;
答案 0 :(得分:11)
您可以创建一个MATCHED
子句,它不会更改任何内容,只更新变量,例如
DECLARE @T1 TABLE (A INT, B INT);
DECLARE @T2 TABLE (A INT, B INT);
DECLARE @T3 TABLE (Action VARCHAR(20), A INT, B INT);
INSERT @T1 VALUES (1, 1), (2, 2), (3, 3);
INSERT @T2 VALUES (1, 0), (2, NULL), (4, 0);
DECLARE @I INT; -- VARIABLE TO UPDATE
MERGE @T2 B
USING @T1 A
ON A.A = B.A
WHEN MATCHED THEN
UPDATE SET @I = 1 -- DO NOTHING MEANINGFUL IN THE UPDATE;
WHEN NOT MATCHED BY TARGET THEN
INSERT (A, B) VALUES (A.A, A.B)
OUTPUT $action, ISNULL(inserted.A, deleted.A), ISNULL(inserted.B, deleted.B) INTO @T3;
SELECT *
FROM @T3;
将返回:
Action A B
INSERT 3 3
UPDATE 1 0
UPDATE 2 NULL
因此,如果您向@TmpTable
添加新列以存储操作,则可以使用以下命令获取匹配的行:
SELECT *
FROM @TmpTable
WHERE Action = 'UPDATE';
您的新行使用:
SELECT *
FROM @TmpTable
WHERE Action = 'INSERT';