我是一个初学者,正在研究有关如何通过此链接计算学生成绩的触发器。 Student_Marks Trigger 更新前触发器的查询工作正常。我正在尝试稍微更改触发器。我想在插入学生分数后计算成绩。 因此,之后触发,而不是更新 。我被卡住了。
我的查询如下:
DELIMITER
$$
CREATE TRIGGER `student_marks`
AFTER INSERT
ON student FOR EACH ROW
BEGIN
SET NEW.Total =NEW.SUB1+NEW.SUB2+NEW.SUB3+NEW.SUB4+NEW.SUB5;
SET NEW.Percentage = NEW.Total/5;
IF NEW.Percentage >=90 THEN
SET NEW.Grade = 'EXCELLENT';
ELSEIF NEW.Percentage>=75 AND NEW.Percentage<90 THEN
SET NEW.Grade = 'VERY GOOD';
ELSEIF NEW.Percentage>=60 AND NEW.Percentage<75 THEN
SET NEW.Grade = 'GOOD';
ELSEIF NEW.Percentage>=40 AND NEW.Percentage<60 THEN
SET NEW.Grade = 'AVERAGE';
ELSE SET NEW.Grade = 'NOT PROMOTED';
END IF;
END;
$$
答案 0 :(得分:0)
您必须使用BEFORE INSERT
而不是AFTER INSERT
来保存新行的计算值。您无法影响行AFTER INSERT
,因为该行已保存。
DELIMITER $$
CREATE TRIGGER `student_marks`
BEFORE INSERT ON student_marks FOR EACH ROW
BEGIN
SET NEW.Total =NEW.SUB1+NEW.SUB2+NEW.SUB3+NEW.SUB4+NEW.SUB5;
SET NEW.Percentage = NEW.Total/5;
IF NEW.Percentage >=90 THEN
SET NEW.Grade = 'EXCELLENT';
ELSEIF NEW.Percentage>=75 AND NEW.Percentage<90 THEN
SET NEW.Grade = 'VERY GOOD';
ELSEIF NEW.Percentage>=60 AND NEW.Percentage<75 THEN
SET NEW.Grade = 'GOOD';
ELSEIF NEW.Percentage>=40 AND NEW.Percentage<60 THEN
SET NEW.Grade = 'AVERAGE';
ELSE
SET NEW.Grade = 'NOT PROMOTED';
END IF;
END;
$$
您还需要更改TRIGGER
的表名(使用INSERT ON student_marks
代替INSERT ON student
)。