插入,删除,更新时的SQL触发器

时间:2011-09-27 00:14:49

标签: sql tsql triggers

我有以下触发器

 ALTER TRIGGER [dbo].[RefreshProject]
   ON  [dbo].[Project] 
   AFTER INSERT,DELETE,UPDATE
AS 
BEGIN
SET NOCOUNT ON
DECLARE @percentage decimal(18,2)
DECLARE @ProjectID int
DECLARE @TASKID int

IF EXISTS(SELECT * FROM Inserted)
    BEGIN
        SELECT @ProjectID = Inserted.ProjectID, @TASKID = ISNULL(Inserted.TASKID,-1) from Inserted join Project on Inserted.ScheduleID = Project.ScheduleID
    END

IF EXISTS(SELECT * FROM Deleted)
    BEGIN
        SELECT @ProjectID = Deleted.ProjectID,@TASKID = ISNULL(Deleted.TASKID,-1) from Deleted join Project on Deleted.ScheduleID = Project.ScheduleID
    END

    BEGIN
         SET @percentage = (SELECT percentage from Project where ProjectID = @ProjectID)
         EXEC LoadSummary @percentage,@ProjectID, @TASKID
    END
END

对于插入和更新,我能够获取修改对象的ProjectID,但是当项目被删除时,我无法获得ProjectID或TaskID ......任何想法我做错了什么?

1 个答案:

答案 0 :(得分:0)

问题是您的触发器是AFTER触发器,这意味着触发触发器时该行已从Project表中删除。因此,您无法将deleted视图加入Project,因为相应的行将不存在。您需要直接从deleted视图中分配所需的变量。

另外,正如上面提到的Mitch的注释,如果一次可以更新多行,您可能希望使用游标迭代inserted / deleted视图中的所有行。或者,如果@@ROWCOUNT大于1,则可以在触发开始时引发错误,以防止多行更新导致触发器行为异常。