记录DELETED记录的计数

时间:2014-02-20 19:26:21

标签: sql-server-2008 tsql

当我尝试运行此

DECLARE @by varchar(20) = 'Myself'

INSERT INTO dbo.MiscLog(LogType, onTable, Message, CreateBy)
   SELECT 
      'Info', 'dbo.History', 
      'There are ' + CONVERT(varchar(20), COUNT(ID)) + ' old records being purged.', @by
   FROM 
       (DELETE FROM dbo.History
        OUTPUT deleted.ID
        WHERE keyDate < dateadd(y, -7, getDate())) H

我得到了

  

Msg 5322,Level 15,State 1,Line 5
  当FROM子句包含嵌套的INSERT,UPDATE,DELETE或MERGE语句时,SELECT子句中不允许使用聚合函数。

2 个答案:

答案 0 :(得分:1)

尝试将已删除记录的副本插入临时表,然后在临时表上运行COUNT()聚合。

SELECT *
INTO #tempLog
   FROM 
       (DELETE FROM dbo.History
        OUTPUT deleted.ID
        WHERE keyDate < dateadd(y, -7, getDate())) H

INSERT INTO dbo.MiscLog(LogType, onTable, Message, CreateBy)
   SELECT 
      'Info', 'dbo.History', 
      'There are ' + CONVERT(varchar(20), COUNT(ID)) + ' old records being purged.', @by
FROM #tempLog

答案 1 :(得分:0)

在表格上创建AFTER DELETE触发器。您可以在deleted查询计数。

SELECT COUNT(*)
FROM   deleted