【数据库基础】数据库完整性控制-触发器

本文来源于MOOC哈工大数据库原理 所有例子可能在DBMS测试都可能报错,这只是博主的个人笔记

触发器在控制数据库的完整性中,可以很好地表现数据库完整性的约束条件intergrity constraint(O,P,A,R);不像静态约束数据库的完整性。AR都时默认的。

定义触发器的基本语法

create triggle triggle_name before|after
{inset|delete|update [of colname{,colname……}]}
on tablename [referencing corr_name_def{,corr_name_def……}]
[for each row|for each statement]
[when (search_condition)]{
    statement|
    begin atomic statement;{statement;……}end;
}

corr_name_def的语法

{
old [row] [as] old_row_name_def
new [row] [as] new_row_name_def
old [table] [as] old_table_name_def
old [table] [as] old_table_name_def
}

eg:Teacher 表中,其工资只能升不能降

create triggle TeaSla before
update of salary 
on Teacher referencing old x new y
for each row
when(x.salary>y.salary){
    begin 
    raise_application_error(-20003,"invalid salary on update);
    end;
}

eg:student(S#,Sname,sumCourse),其中sumCourse 为该同学选修的课程,初始值为0,当给同学没选秀一门课程,sumCourse的值加一。

create triggle stuSumCourse after
insert on Sc
referencing new row newi
begin
update sumCourse=sumCourse+1
where S#=:newi.S#;
end;

eg:student表中的学生更改S#,Sc表中对应的S#也更改

create triggle upSno after
update of S# on student
referencing old oldi new new i
for each row
begin
update Sc set S#=newi.S# where S#=:oldi.S#;
end;

eg:student表中删除一个S#,该生的所有选课成绩都要删除。

create triggle delesno after 
delete of S# on student
referencing old oldi 
for each row
begin
delete from Sc where S#=:oldi.S#;
end;

eg:在student表中如果删除一个S#,该学号对应的选课成绩都设为空。

create triggle setnull after
delete of S# on student
referencing old oldi
for each row
begin
update Sc
set S#=NULL where S#=:oldi.S#;
end;

eg:Dept(D#,Dname,Dean) ,Teacher(T#,Tname,D#,salary);如果Dean为该系教师工资最高的老师,请设计一个触发器实现。

create triggle upsala before
update of Dean on Dept
referencing of new newi
for each row
when(Dean not in (select Tname from Teacher where D#=:newi.D#) and salary >= all(select salary from Teacher where D#=:newi.D#)){
    bengin
    raise_application_error(-20003,"invalid Dean on update");
    end;
}

未完~

你可能感兴趣的:(【数据库基础】数据库完整性控制-触发器)