我有一个触发器,它使用avg()
函数根据course
表中的课程分数来计算学生的gpa。
这里的问题是,当我的触发器执行时,表中的GPA参数为空。
谁能看到这个问题?
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;
根据知识,您的触发器似乎是正确的。但是如果你仔细看看你的插入语句。你正在插入insert into courses (sid, cid, cgrade) values(1, 2550, 0);
这里cgrade的值是0.所以很明显avg(0)是0并且将gpa更新为0.如果你插入几个值,你肯定会在学生表格中以gpa更新avg(CGRADE)。
尝试更多插入来检查像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);
你肯定会得到结果:
1 Mike Brighton 8