触发器==监听器
l
数据库触发器是一个
与表相关联的、存储的
PL/SQL
程序
。每当一个特定的
数据操作语句
(
Insert,update,delete
)
在指定的表上发出时,
Oracle
自动地执行触发器中定义的语句序列
。
l
l
触发器的类型
•
语句级触发器
(1
次
)
•
在指定的操作语句操作之前或之后执行一次,不管这条语句影响了多少行 。
•
•
行级触发器(
FOR EACH ROW(N
次)
•
触发语句作用的每一条记录都被触发。在行级触发器中使用
:old
和
:new
伪记录变量
,
识别值的状态。
l
raise_application_error
(‘-20000’,‘
例外原因
');
触发器作用
l
触发器可用于
•
数据确认
•
安全性检查
CREATE [or REPLACE] TRIGGER 触发器名
{BEFORE| AFTER}
{ INSERT | DELETE| UPDATE [OF 列名]}
ON 表名
[FOR EACH ROW]
PLSQL 块【declare…begin…end;/】
/*
插入一条记录后,自动打印“成功插入一个员工”
*/
create or replace trigger firstTrigger
after insert
on emp
begin
dbms_output.put_line('成功插入一个员工');
end;
/
/*
实施复杂的安全性检查
限制非工作时间向数据库插入(emp)数据:
周末: to_char(sysdate,'day') in ('星期六','星期日')
上班前,下班后:to_number(to_char(sysdate,'hh24')) not between 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;
/
只在行级触发器有用 代表一行
/*
确认数据(涨后的薪水不能少于涨前的薪水)
*/
create or replace trigger checksal
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;
/