Sql Server 2008 MERGE - 获取计数的最佳方式

时间:2009-08-12 20:18:56

标签: sql-server sql-server-2008 merge rowcount

我想知道你们推荐什么是从Sql Server中的MERGE语句获取动作计数的最佳方法。

所以,即我运行一个MERGE,它执行一些插入,一些更新和一些删除,...我希望能够找到HOW MANY插入,HOW MANY更新和多少删除。

最好的方法是什么?

3 个答案:

答案 0 :(得分:33)

您可以在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'
;

这将为每个操作的每个“操作”(插入,更新,删除)提供一行。如果它是很多语句,你也可以输出到@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 clause的详细信息。

马克

答案 1 :(得分:5)

要提取到单个变量,可以使用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行,则可以删除union'nop'行。

答案 2 :(得分:1)

怎么样:

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;

(然后计算结果)

罗布