Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

mysql - What is wrong with the following trigger before an update?

I have to implement the following trigger in mysql before an update is made on the enrollment table

Enforce the constraint that all letter grades must be one ofA, B, C, D (no +/-) in this database). Also ensure that the grade point value matches: A=4.0, B=3.0, C=2.0, D=1.0

  CREATE TABLE enrollment (
  student_id CHAR(4) not null,
  student_name VARCHAR(100) not null,
  course_id CHAR(7) not null,
  enroll_date DATE not null,
  letter_grade CHAR(2),
  grade_points DECIMAL(2,1),
  PRIMARY KEY (student_id, course_id)
);

This is what I have so far:

create trigger letter_grade_checker before update on enrollment 
for each row
  begin
    if ((new.letter_grade != 'A' and new.grade_points != 4.0)
    or (new.letter_grade != 'B' and new.grade_points != 3.0)
    or (new.letter_grade != 'C' and new.grade_points != 2.0)
    or (new.letter_grade != 'D' and new.grade_points != 1.0))
    then SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Invalid grade or grade_points provided';
    end if;
end;

Although it's not working for the following update statement:

UPDATE enrollment SET letter_grade = 'B', grade_points = 3.0
    WHERE student_id = '9999' and course_id = 'CSC-399';
question from:https://stackoverflow.com/questions/65947671/what-is-wrong-with-the-following-trigger-before-an-update

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your boolean expression should be like this

    if  (new.letter_grade != 'A' or new.grade_points != 4.0)
    and (new.letter_grade != 'B' or new.grade_points != 3.0)
    and (new.letter_grade != 'C' or new.grade_points != 2.0)
    and (new.letter_grade != 'D' or new.grade_points != 1.0)
    then ...

Because the logic is

!((a AND b) OR (c AND d)) = !(a AND b) AND !(c AND d) = (!a OR !b) AND (!c OR !d)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...