PL/SQL中触发器的简单使用

来源:互联网 发布:大众网络报 编辑:程序博客网 时间:2024/05/16 10:00
触发器的简单使用 1.触发器介绍数据库触发器是一个与表相关联的、存储的PL/SQL程序。每当一个特定的数据操作语句(Insert,update,delete)在指定的表上发出时,Oracle自动地执行触发器中定义的语句序列。2.触发器的类型(1)语句级触发器在指定的操作语句操作之前或之后执行一次,不管这条语句影响了多少行 。(2)行级触发器(FOR EACH ROW)触发语句作用的每一条记录都被触发。在行级触发器中使用old和new伪记录变量, 识别值的状态。3.触发器的举例(1)限制非工作时间向数据库中插入数据create or replace trigger insertEmpbefore insert on empdeclarebegin       if(to_char(sysdate,'day') in ('星期四','星期五')) then              raise_application_error(-20001,'不能插入数据');       end if;end;测试:SQL> insert into emp(empno,deptno) values(14,10); insert into emp(empno,deptno) values(14,10)ORA-20001: 不能插入数据ORA-06512: 在 "TEST1.INSERTEMP", line 5ORA-04088: 触发器 'TEST1.INSERTEMP' 执行过程中出错(2)更改的数据不能小于原原有的值create or replace trigger updateEmp  before update on emp    for each rowdeclare  -- local variables herebegin  if :new.sal< :old.sal then    raise_application_error(-20002,'更改的数据不能小于原原有的值');    end if;end updateEmp;测试:SQL> update emp set sal=200 where empno=7369; update emp set sal=200 where empno=7369 ORA-20002: 更改的数据不能小于原原有的值ORA-06512: 在 "TEST1.UPDATEEMP", line 5ORA-04088: 触发器 'TEST1.UPDATEEMP' 执行过程中出错(3) 指定部门插入的员工数不能大于5create or replace trigger limite  before insert on emp    for each rowdeclare  -- local variables here  cursor cl is select count(*) from emp group by deptno; emp_count emp.empno%type;begin  open cl;  fetch cl into emp_count;  if (emp_count>5) then          raise_application_error(-20002,'员工个数不能多余5个');  end if;  close cl;end limite;或create or replace trigger limitebefore insert on emp  for each rowdeclarenum number;beginselect count(*) into num from emp where deptno=:new.deptno; if(num>=5) then        raise_application_error(-20002,'员工个数不能多余5个'); end if;end limite;结果和以上的格式一样