我正在编写一个触发器来将一个表的记录计数存储为另一个表中的列,以加快大型数据库上的一些报告查询。
这是我到目前为止所得到的,它在删除时工作得很好,但我也需要它在插入时工作。我需要使用单独的触发器吗?另外,是否有必要使用游标,还是有更有效的方法?
谢谢!
ALTER TRIGGER [dbo].[updateSourceTotals]
ON [dbo].imports
AFTER INSERT, DELETE
AS
BEGIN
SET NOCOUNT ON;
DECLARE @sourceId int;
DECLARE deleteCursor CURSOR FOR SELECT DISTINCT sourceId FROM deleted
OPEN deleteCursor
FETCH NEXT FROM deleteCursor INTO @sourceId
WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE sources
SET totalImports = (
SELECT COUNT(*)
FROM imports
WHERE sourceId = @sourceId
)
WHERE id = @sourceId
FETCH NEXT FROM deleteCursor INTO @sourceId
END
CLOSE deleteCursor
DEALLOCATE deleteCursor
END
GO