PL/SQL Triggers with aggregate function

时光怂恿深爱的人放手 提交于 2019-12-24 09:36:46

问题


I have a trigger that uses the avg() function to calculate a student's gpa based on the number of course scores that are in the course table.

Problem here is, when my trigger executes, the GPA parameter in the table is empty.

Could anyone see the issue?

drop table courses;
drop table student;
drop table assignments;

create table student (sid integer, sname char(10), saddress char(10), gpa integer);
create table courses (sid integer, cid integer, cgrade integer);
create table assignments ( sid integer, cid integer, aid integer, agrade integer);


create or replace trigger updategpa before insert or update of cgrade on courses for each row
    begin
        if inserting then
            update student set gpa = (select avg(cgrade) from courses where courses.sid = student.sid) where sid = :new.sid;
        elsif inserting then
            update student set gpa = (select avg(cgrade) from courses where courses.sid = student.sid) where sid = :new.sid;
        elsif deleting then
            delete from student where sid = :new.sid;
        end if;
    end;
/
show errors;


insert into student (sid, sname, saddress, gpa) values (1, 'Mike', 'Brighton', 0);
insert into courses (sid, cid, cgrade) values(1, 2550, 0);
insert into assignments values(1, 2550, 1, 70);
insert into assignments values(1, 2550, 2, 80);

select * from courses;
select * from student;
select * from assignments;

update assignments set agrade = agrade + 5;

select * from courses;
select * from student;
select * from assignments;

回答1:


Your trigger seems to be correct as per knowledge. But if you see carefully with your insert statement. You are inserting insert into courses (sid, cid, cgrade) values(1, 2550, 0); here value of cgrade is 0. So obviously avg(0) is 0 and updating gpa as 0. if you insert couple of values you will definitely get the avg(CGRADE) updated in gpa in students table.

try out couple of more inserts to check like insert into courses (sid, cid, cgrade) values(1, 2551, 10); insert into courses (sid, cid, cgrade) values(1, 2551, 15); insert into courses (sid, cid, cgrade) values(1, 2551, 20);

you will definitely get the result:

1 Mike Brighton 8



来源:https://stackoverflow.com/questions/49103180/pl-sql-triggers-with-aggregate-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!