触发器定义:触发器是特定事件出现的时候,自动执行的代码块。类似于存储过程,但是用户不能直接调用他们。
触发器功能:1、答应/限制对表的修改;2、自动生成派生列,比如自增字段;3、强制数据一致性;4、提供审计和日志记录;5、防止无效的事务处理;6、启用复杂的业务逻辑。
触发器的组成部分:1、触发器名称;2、 触发语句;3、触发器限制;4、 触发操作。
触发器类型:1、语句触发器;2、 行触发器;3、 instead of 触发器;4、 系统条件触发器;5、用户事件触发器。
触发器中new和old默认值如下:
Data Operation Old value New value
insert null Inserted value
update Value before update Value after update
delete Value before delete null
实例---行触发器
create or replace trigger tri_em_branch
after insert or update or delete
--after在数据库动作之后触发器执行;insert,update,delete在插入,修改,删除后触发器执行。
on em_branch --数据库触发器所在的表
for each row --对表的每一行触发器执行一次。
/*將組別資料寫入生管組別檔*/
Declare
--变量声明
v_fact_no em_branch.fact_no%type;
v_sec_no em_branch.branch_no%type;
v_sec_name em_branch.branch_nm%type;
v_dept_no em_branch.dept_no%type;
v_floor_no em_branch.floor_no%type;
v_fact_no_d em_pri_fact_d.pri_fact_no%type ;
v_if_flag em_branch.if_flag%type;
begin
if updating or deleting then
v_fact_no :=:old.fact_no;
v_sec_no :=:old.branch_no;
v_if_flag :=:old.if_flag;
end if;
if updating or inserting then
v_fact_no :=:new.fact_no;
v_sec_no :=:new.branch_no;
v_sec_name :=:new.branch_nm;
v_dept_no :=:new.dept_no;
v_floor_no :=:new.floor_no;
v_if_flag :=:new.if_flag;
if substr(v_sec_no,1,1) = 'A' then
v_fact_no_d := '0213' ;
else
if substr(v_sec_no,1,1) = 'C' then
v_fact_no_d := '0215' ;
else
v_fact_no_d := '0214' ;
end if;
end if ;
end if;
if updating then
update sg_pro_sec@lkerp_43
set sec_name = v_sec_name,
dept_no = v_dept_no,
floor_no = v_floor_no,
if_flag = v_if_flag
where fact_no = v_fact_no
and sec_no = v_sec_no;
update em_pri_fact_d
set branch_nm = v_sec_name,
if_flag = v_if_flag
where fact_no = v_fact_no
and branch_no = v_sec_no ;
update em_pnl
set if_flag = v_if_flag
where fact_no = v_fact_no and branch_no = v_sec_no;
end if ;
if inserting then
insert into em_pri_fact_d(fact_no,pri_fact_no,branch_no,branch_nm,if_flag)
values(v_fact_no,v_fact_no_d,v_sec_no,v_sec_name,v_if_flag) ;
insert into sg_pro_sec@lkerp_43(fact_no,sec_no,sec_name,dept_no,floor_no,if_flag)
values(v_fact_no,v_sec_no,v_sec_name,v_dept_no,v_floor_no,v_if_flag);
end if;
if deleting then
delete from sg_pro_sec@lkerp_43 where fact_no = v_fact_no and sec_no = v_sec_no;
delete from em_pri_fact_d where fact_no = v_fact_no and branch_no = v_sec_no;
end if;
end em_branch;