Oracle实验八 触发器
第1关:触发器之抛出异常
1、创建触发器tr_Student_update,当修改Student表时,不能修改20岁以上(包括20岁)的同学的系别。抛出的异常提示为:不能修改20岁以上的同学系别。
create or replace trigger tr_Student_update
before update on Student
for each row
begin
if(:old.sage>=20) then
raise_application_error(-20000,'不能修改20岁以上的同学系别。');
end if;
end;
2、创建触发器tr_Course_Insert,当插入Course表数据是,课程号以X开头的课程,必须要有先行课。抛出异常提示为:课程号以X开头的课程,先行课不能为空。
create or replace trigger tr_Course_Insert
before insert on Course
for each row
begin
if(:new.cno like 'X%' and :new.cpno is null) then
raise_application_error(-20000,'课程号以X开头的课程,先行课不能为空。');
end if;
end;
3、创建触发器tr_SC_Delete,规定不能删除数据库课程的选课信息。抛出的异常提示为:不能删除数据库课程的选课信息。
create or replace trigger tr_SC_Delete
before delete on SC
for each row
declare
tcno SC.cno%type;
begin
select cno into tcno from Course where cname='数据库';
if(:old.cno=tcno) then
raise_application_error(-20000,'不能删除数据库课程的选课信息。');
end if;
end;
4、创建触发器tr_SC_Update,当修改学生考试成绩时,若修改的学生是CS系的学生,则成绩只能增加,不能减少,并且不能将成绩修改为null。若不是CS系的同学,则不受控制。若成绩修改比原成绩小,则抛出的异常提示为:CS系学生的成绩只能增加不能减少。若将成绩修改为null,则抛出的异常提示为:CS系学生的成绩不能修改为空。
create or replace trigger tr_SC_Update
after update of grade on SC
for each row
declare
tsdept Student.sdept%type;
begin
select sdept into tsdept from Student where sno=:old.sno;
if(tsdept='CS') then
if(:new.grade<:old.grade and :new.grade is not null) then
raise_application_error(-20000,'CS系学生的成绩只能增加不能减少。');
end if;
if(:new.grade is null) then
raise_application_error(-20000,'CS系学生的成绩不能修改为空。');
end if;
end if;
end;
第2关:触发器之选课数及级联删除
1、创建student表上的删除触发器,当删除学生信息时,先将该学生的选课信息删除。
测试触发器:在Student表中删除001号同学
create or replace trigger tr_Student_Delete
before delete on Student
for each row
begin
if deleting then
delete from SC where sno=:old.sno;
end if;
end;
--***********测试语句**************************************
delete from Student where sno='001';
--***********End*******************************************
commit;
2、创建SC表的增删改触发器,维护冗余数据。在Student表中新建Scnt列(学生选课门数,类型为int,初值为0),并初始化Scnt列数据。在触发器中维护这一冗余列,保证Scnt列数据的正确。
测试触发器:
1、为019号同学选择C01课程,成绩为空。
2、将014同学选择C01课程记录的学号修改为015。
3、删除013学生的所有选课信息。
--*******