Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

oracle - Create a trigger that automatically assign grade in PL/SQL

I want to make a trigger that when I update student's mark in a table.. then it will automatically assign a grade.

CREATE OR ALTER TRIGGER calculate_grade
AFTER INSERT OR UPDATE ON student_subject
BEGIN
    UPDATE student_subject SET grade =
    CASE
        WHEN (new.firstterm+new.secondterm) >= 80 THEN 'A'
        WHEN (new.firstterm+new.secondterm) >= 65 AND (new.firstterm+new.secondterm) < 80 THEN 'B'
        WHEN (new.firstterm+new.secondterm) >= 50 AND (new.firstterm+new.secondterm) < 65 THEN 'C'
        WHEN (new.firstterm+new.secondterm) >= 40 AND (new.firstterm+new.secondterm) < 50 THEN 'D'
        WHEN (new.firstterm+new.secondterm) >= 20 AND (new.firstterm+new.secondterm) < 40 THEN 'E'
        ELSE 'F'
    END
END

but it found it errors.. how do I fix it

question from:https://stackoverflow.com/questions/65946818/create-a-trigger-that-automatically-assign-grade-in-pl-sql

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

1 Reply

0 votes
by (71.8m points)

For this use case I would recommend using virtual column. You will save on space (only metadata are stored about the column) and grade will be always in sync (someone can disable trigger for a while and this could cause problems with data integrity using trigger based approach). DML on the table will be also faster.

create table t(
  id number primary key,
  firstterm number,
  secondterm number,
  grade char(1) generated always as (
        case
            when firstterm + secondterm >= 80 then 'A'
            when firstterm + secondterm >= 65 then 'B'
            when firstterm + secondterm >= 50 then 'C'
            when firstterm + secondterm >= 40 then 'D'
            when firstterm + secondterm >= 20 then 'E'
            when firstterm + secondterm >= 0  then 'F'
            else null
        end
  ) virtual
)

sqlfiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...