SQL Trigger on Insert, Delete, Updated
I have the following trigger
ALTER TRIGGER [dbo].[RefreshProject]
ON [dbo].[Project]
AFTER INSERT,DELETE,UPDAT开发者_如何学CE
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
For Inserts and updates I am able to get the ProjectID of the modified object, however when an item is deleted, I can not get the ProjectID or TaskID... Any Idea what I'm doing wrong?
The problem is that your trigger is an AFTER
trigger, which means that the row has already been deleted from the Project
table by the time the trigger is fired. So, you can't join the deleted
view to Project
, because the corresponding row won't exist. You will need to assign the variables you want directly from the deleted
view.
Also, as Mitch's note mentions above, you may want to use a cursor to iterate over all rows in the inserted
/deleted
views if multiple rows can be updated at a time. Alternatively, you could raise an error at the beginning of your trigger if @@ROWCOUNT
is greater than one, to prevent multiple row updates from causing your trigger to misbehave.
精彩评论