Previously, I have created 3 triggers individually for insert, update, and delete actions.
The triggers are supposed to modify a value in another table when one of these happen.
When I try to create one combined trigger for all 3 actions (insert, update, and delete), I get many errors when trying to execute it. I've tried both case statements and if statements, but cannot tell what is going wrong.
CREATE TRIGGER multipurposeCourseEnrollment
ON courseEnrollment AFTER INSERT, DELETE, UPDATE AS
BEGIN
IF EXISTS(SELECT courseID FROM DELETED) AND EXISTS(SELECT courseID FROM INSERTED)
THEN
DECLARE @oldCourseID INT
DECLARE @newCourseID INT
SELECT @oldCourseID = (SELECT courseID FROM DELETED)
SELECT @newCourseID = (SELECT courseID FROM INSERTED)
BEGIN
UPDATE courses SET courseOpenSeats = (courseOpenSeats +1)
WHERE courseID = @oldCourseID
UPDATE courses SET courseOpenSeats = (courseOpenSeats -1)
WHERE courseID = @newCourseID AND courseOpenSeats>0
END
ELSE
IF EXISTS(SELECT courseID FROM DELETED)
THEN
DECLARE @courseIDDel INT
SELECT @courseIDDel = (SELECT courseID FROM DELETED)
BEGIN
UPDATE courses SET courseOpenSeats = (courseOpenSeats +1)
WHERE courseID = @courseIDDel
END
ELSE
IF EXISTS(SELECT courseID FROM UPDATED)
THEN
DECLARE @courseID INT
SELECT @courseID = (SELECT courseID FROM UPDATED)
BEGIN
UPDATE courses SET courseOpenSeats = (courseOpenSeats - 1)
WHERE courseID = @courseID AND courseOpenSeats>0
END
ELSE
END)
END;
One problem may be how I declared the @variables
. Not sure if this is correct.
The error I get is :
Incorrect syntax near the keyword 'THEN'.
I also get this for ELSE