我想知道你们会推荐什么作为从 Sql Server 中的 MERGE 语句中获取操作计数的最佳方法。
所以,即我运行一个 MERGE,它执行一些插入、一些更新和一些删除,...我希望能够找出多少插入、多少更新和多少删除。
最好的方法是什么?
我想知道你们会推荐什么作为从 Sql Server 中的 MERGE 语句中获取操作计数的最佳方法。
所以,即我运行一个 MERGE,它执行一些插入、一些更新和一些删除,...我希望能够找出多少插入、多少更新和多少删除。
最好的方法是什么?
你可以在你的 MERGE 语句中指定一个 OUTPUT 子句,并获得一份关于 MERGE 期间所做工作的输出报告。
MERGE (targetTable) AS t
USING (sourceTable) AS s
ON t.ID = s.ID
WHEN MATCHED THEN
(some statements)
WHEN NOT MATCHED THEN
(some statements)
OUTPUT
$action, inserted.ID 'inserted', deleted.ID 'deleted'
;
这将为每个操作的每个“操作”(插入、更新、删除)提供一行。如果语句很多,您也可以 OUTPUT INTO @tableVar 然后查看表变量。
DECLARE @tableVar TABLE (MergeAction VARCHAR(20), InsertedID INT, DeletedID INT)
MERGE (targetTable) AS t
USING (sourceTable) AS s
ON t.ID = s.ID
WHEN MATCHED THEN
(some statements)
WHEN NOT MATCHED THEN
(some statements)
OUTPUT
$action, inserted.ID 'inserted', deleted.ID 'deleted' INTO @tableVar
;
SELECT MergeAction, COUNT(*)
FROM @tableVar
GROUP BY MergeAction
查看联机丛书以获取有关MERGE语句和OUTPUT 子句的详细信息。
马克
要提取到单个变量中,可以使用 pivot 通过 marc_s 发布过程答案:
declare
@mergeResultsTable table (MergeAction VARCHAR(20));
declare
@insertCount int,
@updateCount int,
@deleteCount int;
merge ...
output $action into @mergeResultsTable;
select @insertCount = [INSERT],
@updateCount = [UPDATE],
@deleteCount = [DELETE]
from (select 'NOOP' MergeAction -- row for null merge into null
union all
select * from @mergeResultsTable) mergeResultsPlusEmptyRow
pivot (count(MergeAction)
for MergeAction in ([INSERT],[UPDATE],[DELETE]))
as mergeResultsPivot;
如果 init vars 为 0 或知道源表或目标表有 >0 行,则可以删除联合“noop”行。
怎么样:
INSERT YourResultsTable (action, cnt)
SELECT action, count(*)
FROM
(
MERGE (targetTable) AS t
USING (sourceTable) AS s
ON t.ID = s.ID
WHEN MATCHED THEN (some statements)
WHEN NOT MATCHED THEN (some statements)
OUTPUT $action as action, inserted.ID as ins, deleted.ID as del
) m
GROUP BY action;
[编辑]好的,所以试试:
INSERT YourResultsTable (action)
SELECT action
FROM
(
MERGE (targetTable) AS t
USING (sourceTable) AS s
ON t.ID = s.ID
WHEN MATCHED THEN (some statements)
WHEN NOT MATCHED THEN (some statements)
OUTPUT $action as action, inserted.ID as ins, deleted.ID as del
) m;
(然后计算结果)
抢