- 触发器是一个与表相关联的、存储的PL/SQL程序。每当一个特定的数据操作语句(insert、update、delete)在指定的表上发出时,Oracle自动地执行触发器中定义的语句序列。
eg:每当成功插入新员工后,自动打印”成功插入新员工”。
create trigger newemp
after insert
on emp
declare
begin
dbms_output.put_line(‘成功插入新员工’);
end;
/ - 触发器的应用场景
(1)复杂的安全性检查
(2)数据的确认
(3)数据库的审计
(4)数据的备份和同步 - 触发器的语法
CREATE [ OR REPLACE ] TRIGGER 触发器名
{BEFORE | AFTER} {DELETE | INSERT | UPDATE [ OF 列名]}
ON 表名
[FOR EACH ROW [WHEN (条件)]]
PLSQL 块 - 触发器的类型
[1] 语句级触发器:在指定的操作语句操作之前或之后执行一次,不管这条语句影响了多少行。针对的是表
[2] 行级触发器:触发语句作用的每一条记录都被触发。在行级触发器中使用:old和:new伪记录变量,识别值的状态。针对的是行
:old和:new 代表同一条记录
:old 表示操作该行之前这一行的值
:new 表示操作该行之后这一行的值
区别:有FOR EACH ROW[ WHEN (条件)],是行级触发器,没有则是语句级触发器 案列
(1)复杂的安全性检查:禁止在非工作时间插入数据
周末:to_char(sysdate,’day’) in (’星期六’,’星期日’)
上班前,下班后:to_number(to_char(sysdate,’hh24’)) not between 9 and 18create 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 --禁止insert新员工,-20001是错误代码(-20001~-20099) raise_application_error(-20001,'禁止在非工作时间插入新员工') end if; end; /
(2)数据的确认:涨工资不能越涨越少
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 table audit_info
(
information varchar(200)
);create or replace trigger audit_emp_salary after update on emp for each row begin 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; /
ORACLE触发器
最新推荐文章于 2024-05-14 23:08:08 发布