以前,我为插入、更新和删除操作分别创建了 3 个触发器。
当其中一个发生时,触发器应该修改另一个表中的值。
当我尝试为所有 3 个操作(插入、更新和删除)创建一个组合触发器时,尝试执行它时会出现许多错误。我已经尝试过 case 语句和 if 语句,但无法判断出了什么问题。
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;
一个问题可能是我如何声明@variables
. 不确定这是否正确。
我得到的错误是:
关键字“THEN”附近的语法不正确。
我也得到这个ELSE