1

我想做的是管理新生的成绩归属。如果插入的包含学生 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 语句。我们将 null 值更新为 9 级,将等级 > 9 或 > 12 更新为 NULL

4

2 回答 2

2

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

UPDATE Students
     SET grade = 9 
   WHERE grade IS NULL;

= NULL用and证明IS NULLhttp ://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
于 2013-03-09T14:19:16.870 回答
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;
于 2016-01-26T13:27:42.637 回答