Oracle 触发器
触发器的应用场景
创建触发器
create trigger saynewemp
after insert
on emp
declare
begin
dbms_output.put_line("成功插入新员工");
end;
语法
类型
- 语句级触发器
在指定的操作语句操作之前或之后执行一次,不管这条语句影响了多少行。
- 行级触发器
触发语句作用的每一条记录都被触发。在行级触发器中使用:old 和 :new 伪记录变量,识别值的状态。
应用
应用场景1: 实施复杂的安全性检查(禁止在非工作时间插入新员工)
/*
1. 周末: to_char(sysdate,'day') in ('星期六,星期日')
2. 上班前,下班后 to_number( to_char(sysdate,'hh24')) not beween 9 and 18
*/
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 18 then
--禁止插入新员工
raise_application_error(-20001,'禁止在非工作时间插入新员工');
end if;
end;
应用场景2: 涨工资不能越来越少
/*
:old 和 :new 代表同一条记录
:old 表示操作该行之前,这一行的值
: new 表示操作该行之后,这一行的值
*/
create or replace trigger checksalary
before update
on emp
for each row
begin
-- if 涨后的薪水 < 涨前的薪水 then
if :new.sal < :old.sal then
raise_application_error(-20002,'涨后的薪水不能少于涨前的薪水,涨后的薪水:'|| :new.sal || '涨前的薪水:' :old.sal );
end if;
end;
应用场景3: 当涨后的薪水超过6000块的时候,审计该员工的信息
create or replace trigger do_auid_emp_salary
after update
on emp
for each row
begin
--当涨后的薪水大于6000,插入审计信息
if :new.sal > 6000 then
insert into audit_info values(:new.empno || '' ||:new.ename|| '' ||:new.sal);
end if;
end;
应用场景4:数据库的备份和同步
create or replace trigger sync_salary
after update
on emp
for each row
begin
--当主表更新后。自行更新备份表
update emp_back set sal=:new.sal where empno=:new.empno;
end;
/
有不对的地方,欢迎大家一起讨论。 最后,欢迎大家关注我的微信号“涛涛之海”,您的点赞,收藏,转发就是对我的最大鼓励。