我想要做的是管理新学生的成绩归属。如果插入的包含学生ID和成绩的元组的成绩值小于9或大于12,我们希望将值更改为NULL。同时,如果插入的元组具有等级null值,我们希望将其更改为9。
以下代码有什么问题?
CREATE TRIGGER R1
AFTER INSERT ON Students
FOR EACH ROW
BEGIN
UPDATE Students
SET grade = NULL
WHERE grade < 9 OR grade > 12;
UPDATE Students
SET grade = 9
WHERE grade = NULL;
END;
请注意,在执行INSERT之后,必须在Student表上执行两个UPDATE语句。我们将空值更新为9级和等级&gt; 9或&gt; 12要更新为NULL
答案 0 :(得分:2)
您应该将第二个条件从= NULL
替换为IS NULL
:
UPDATE Students
SET grade = 9
WHERE grade IS NULL;
使用= NULL
和IS NULL
证明:http://sqlfiddle.com/#!5/a51de/1
其他解决方案:
http://sqlfiddle.com/#!5/78288/1
CREATE TRIGGER TStudents3
AFTER INSERT ON Students3
FOR EACH ROW
/* we check update conditions here */
WHEN NEW.grade IS NULL
OR NEW.grade < 9
OR NEW.grade > 12
BEGIN
UPDATE Students3
SET grade =
CASE
WHEN grade IS NULL THEN 9
/* actually you could drop this 2 lines, because a missing ELSE returns NULL: */
WHEN grade < 9 OR grade > 12 THEN NULL
ELSE grade
END
/* We just want to update the freshly inserted row, not all row! */
WHERE id = NEW.id;
END
答案 1 :(得分:0)
另一种方法是在where子句中移动条件:
CREATE TRIGGER tr1 AFTER INSERT ON Student
BEGIN
UPDATE Student SET grade = null WHERE id = NEW.id and (new.grade<9 or new.grade>12);
UPDATE Student SET grade = 9 WHERE id = NEW.id and new.grade is null;
END;