oracle 触发器 详解

来源:互联网 发布:网络教育本科怎么报名 编辑:程序博客网 时间:2024/06/05 07:07

一、触发器
数据库触发器是一个与表相关联的、存储的PL/SQL程序。
每当一个特定的数据操作语句(insert、update、delete)在指定的表上发出时,oracle自动执行触发器中定义的程序。
例子:每当往员工表(emp)中插入一条数据,打印“成功插入新员工”

create trigger saynewempafter insert on empdeclarebegin    dbms_output.put_line('成功插入新员工');end;

二、触发器的具体应用场景

1.复杂的安全性检查
2.数据的确认
3.数据库的审计
4.数据的备份和同步

三、触发器的语法

create [or replace] trigger 触发器名{before|after}{delete|insert|update[列名]}on 表名[for each row[where(条件)]]PL/SQL语法块

1.语句级触发器

在指定的操作语句操作之前或之后执行一次,不管这条语句影响了多少行。

2.行级触发器

[for each row[where(条件)]]

触发语句作用的每一条记录都被触发。在行级触发器中使用:old 和 :new 伪记录变量,识别值的状态。

四、案例
1.禁止在非工作时间插入新员工

--周六和周日不能插入新员工to_char(sysdate,'day') in ('星期六','星期日')--上班前后下班后:to_number(to_char(sysdate,'hh24')) not between 9 and 18--语句级触发器create or replace trigger securityempbefore insert on empdeclare--没有变量的话,declare可以省略begin    if to_char(sysdate,'day') in ('星期六','星期日') then        or to_number(to_char(sysdate,'hh24')) not between 9 and 18    raise_application_error(-20001,'禁止在非工作时间插入新员工');    end if;end; 

2.涨工资不能越涨越少

--行级触发器create or replace trigger checksalarybefore update on empfor each row declare begin  -- :old 表示操作该行之前,这一行的值  -- :new 表示操作该行之后,这一行的值   if :new.sal < :old.sal then   raise_application_erro(-20002,'涨后的薪水不能少于涨前的薪水');   end if; end;

3.给员工涨工资,当涨后的薪水超过6000块钱的时候,审计该员工的信息

--创建表,用于保存审计信息create table audit_info(information varchar2(200));--行级触发器create or replace trigger do_audit_emp_salaryafter update  on empfor each row begin    if :new.sal >6000 then        insert into audit_info values(:new.empno||' '||:new.sal);    end if;end;
0 0
原创粉丝点击