触发器

  数据库触发器是一个与表相关联的、存储的PL/SQL程序。每当一个特定的数据操作语句(insert、update、delete)

在指定的表上发出时,oracle自动地执行触发器中定义的语句序列。

触发器作用

1. 数据确认

2. 实施复杂的安全性检查

3. 做审计,跟踪表上所有的数据操作等

4. 数据的备份和同步

触发器类型

1. 语句级触发器:

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

2. 行级触发器(for each row):

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

 

触发器语法

create [or replace] trigger 触发器名
{before|after}
{delete|insert|update[of 列名]}
on 表名
[for each row [where(条件)]]
declare
    ......
begin
    PLSQL块
end [触发器名];

 触发器应用一

/*
数据的确认
涨后的薪水不能少于涨前的薪水
*/
create or replace trigger checksalary
  before update
  on emp
  for each row
begin
   if :new.sal < :old.sal then
    raise_application_error(-20001,'涨后的薪水不能少于涨前的薪水。涨前:'||:old.sal||'   涨后:'||:new.sal);
  end if;
end checksalary;

触发器应用二

/*
实施复杂的安全性检查
禁止在非工作时间 插入新员工
*/
create or replace trigger securityemp
  before insert  
  on emp   

begin
  if to_char(sysdate,'day') in('星期六','星期日','星期四') or
     to_number(to_char(sysdate,'hh24')) not between 9 and 17 then
     raise_application_error(-20002,'禁止在非工作时间插入新员工');
  end if;
end securityemp;

 

 

posted @ 2018-08-02 11:58  风雪夜_归人  阅读(245)  评论(0编辑  收藏  举报