gpt4 book ai didi

sqlite - SQLite 中的多个更新触发器

转载 作者:行者123 更新时间:2023-12-01 22:43:17 25 4
gpt4 key购买 nike

我想做的是管理新生的成绩归属。如果插入的包含学生 ID 和成绩的元组的成绩值小于 9 或大于 12,我们希望将该值更改为 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 级,并将等级 > 9 或 > 12 更新为 NULL

最佳答案

您应该将第二个条件从 = NULL 替换为 IS NULL:

UPDATE Students
SET grade = 9
WHERE grade IS NULL;

= NULLIS 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

关于sqlite - SQLite 中的多个更新触发器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15311566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com