2014-02-20 180 views
0

當我嘗試運行此刪除了記錄計數記錄

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 

我得到

消息5322,級別15,狀態1,行5
一個聚集函數是不是在允許的SELECT子句包含嵌套的INSERT,UPDATE,DELETE或MERGE語句。

回答

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 
0

在表上創建一個AFTER DELETE觸發器。您可以查詢deleted的計數。

SELECT COUNT(*) 
FROM deleted