数据库触发器是一个与表相关联的、存储的PL/SQL程序。每当一个特定的数据操作语句(Insert,update,delete)在指定的表上发出时,Oracle自动地执行触发器中定义的语句序列。
1.触发器作用
l 数据确认
l 实施复杂的安全性检查
l 做审计,跟踪表上所做的数据操作等
l 数据的备份和同步
2.触发器的类型
语句级触发器 :在指定的操作语句操作之前或之后执行一次,不管这条语句影响 了多少行 。
行级触发器(FOR EACH ROW) :触发语句作用的每一条记录都被触发。在行级触 发器中使用old和new伪记录变量, 识别值的状态。
语法:
CREATE [or REPLACE] TRIGGER 触发器名
{BEFORE | AFTER}
{DELETE | INSERT | UPDATE [OF 列名]}
ON 表名
[FOR EACH ROW [WHEN(条件) ] ]
declare
……
begin
PLSQL 块
End 触发器名
范例:插入员工后打印一句话“一个新员工插入成功”
create or replace trigger testTrigger
after insert on person
declare
-- local variables here
begin
dbms_output.put_line('一个员工被插入');
end testTrigger;
范例:不能在休息时间插入员工
create or replace trigger validInsertPerson
before insert on person
declare
weekend varchar2(10);
begin
select to_char(sysdate, 'day') into weekend from dual;
if weekend in ('星期一') then
raise_application_error(-20001, '不能在非法时间插入员工');
end if;
end validInsertPerson;
当执行插入时会报错
在触发器中触发语句与伪记录变量的值
触发语句 | :old | :new |
Insert | 所有字段都是空(null) | 将要插入的数据 |
Update | 更新以前该行的值 | 更新后的值 |
delete | 删除以前该行的值 | 所有字段都是空(null) |
范例:判断员工涨工资之后的工资的值一定要大于涨工资之前的工资
create or replace trigger addsal4p
before update of sal on myemp
for each row
begin
if :old.sal >= :new.sal then
raise_application_error(-20002, '涨前的工资不能大于涨后的工资');
end if;
end;
调用
update myemp t set t.sal = t.sal - 1;
3.触发器实际应用
需求:使用序列,触发器来模拟mysql中自增效果
1. 创建序列
1、建立表
复制代码 代码如下:create table user
(
id number(6) not null,
name varchar2(30) not null primary key
)
2、建立序列SEQUENCE
代码如下:
create sequence user_seq increment by 1 start with 1 minvalue 1 maxvalue 9999999999999 nocache order;
2.创建自增的触发器
分析:创建一个基于该表的before insert 触发器,在触发器中使用刚创建的SEQUENCE。
代码如下:
create or replace trigger user_trigger
before insert on user
for each row
begin
select user_seq.nextval into:new.id from sys.dual ;
end;
3.测试效果
insert into itcastuser(name) values('aa');
commit;
insert into itcastuser(name) values('bb');
commit;