SQL触发器性能

时间:2011-12-13 22:07:29

标签: sql-server-2008

我在桌面上有一个触发器,基本上就是这个

ALTER TRIGGER xx
FOR UPDATE,DELETE,INSERT
AS
   DELETE FROM other WHERE id in (SELECT id from deleted)
   DELETE FROM other WHERE id in (SELECT id from inserted)
   INSERT INTO other() VALUES() WHERE id in (SELECT id from inserted)

GO

插入时(20秒)它运行得非常慢。删除很快。在我身边试着这样做:

ALTER TRIGER xx
FOR UPDATE,DELETE,INSERT
AS
   DECLARE @tinserted TABLE ( id int) 
   INSERT INTO @tinserted select id from inserted;
   DELETE FROM other WHERE id in (SELECT id from deleted)
   DELETE FROM other WHERE id in (SELECT id from inserted)
   INSERT INTO other() VALUES() WHERE id in (SELECT id from @tinserted)

GO

通过使用表变量,它现在可以立即运行(不到1秒)。

我不确定为什么。是否有任何理由为什么更改为表变量会产生这样的差异?

1 个答案:

答案 0 :(得分:4)

不确定为什么你需要WHERT子句来进行INSERT操作。

INSERT INTO other(column1, column2, ...)
    SELECT column1, column2, ...
        FROM inserted;