一.触发器是什么
触发器是数据库中,隐含被执行的存储过程存储过程,当发生特定的事件时,orcle会自动执行触发器相对应的代码.
二.触发器的分类
1.DML触发器
2.DDL触发器
3.INSTEAD 触发器
4.事件触发器
三.例子
CREATE OR REPLACE TRIGGER upd_esp_category
BEFORE INSERT OR UPDATE
OF email
ON ex_edm_task_detail
FOR EACH ROW
DECLARE
v_category VARCHAR2(64);
BEGIN
SELECT esp_name INTO v_category
FROM ex_edm_esp
WHERE mail_suffix=SUBSTR(:new.email,INSTR(:new.email,'@',1,1)+1, LENGTH(:new.email));
:new.category := v_category;
EXCEPTION
WHEN no_data_found THEN
:new.category := '未知';
WHEN too_many_rows THEN
:new.category := '未知';
WHEN OTHERS THEN
:new.category := '未知';
END; 再来一个例子:
create or replace trigger wf_tri_user_list before insert or update or delete on user_list
for each row
declare
uid varchar2(10); useq varchar2(10); asql varchar2(200); namea varchar2(200); nameb varchar2(200);
begin
namea:=NULL;
nameb:=NULL;
if inserting then
insert into wflow.bpm_org_user(userid,username,diaplayname,seq) values(:NEW.user_id,:NEW.user_name,:NEW.user_realname,:NEW.user_id);
dbms_output.put_line('insert trigger is chufale ..');
end if;
if updating then
if (:NEW.user_name<>:OLD.user_name) and (:NEW.user_realname<>:OLD.user_realname) then
namea:=:NEW.user_name;
nameb:=:NEW.user_realname;
asql:='update wflow.bpm_org_user set diaplayname=:1 where username=:2';
execute immediate asql using namea,nameb;
else
if :NEW.user_name<>:OLD.user_name then
namea:=:NEW.user_name;
asql:='update wflow.bpm_org_user set user_name=:1 where username=:2';
execute immediate asql using namea;
else
if :NEW.user_realname<>:OLD.user_realname then
nameb:=:NEW.user_realname;
asql:='update wflow.bpm_org_user set diaplayname=:1 where username=:2';
execute immediate asql using nameb,:OLD.user_id;
end if;
end if;
end if;
end if;
if deleting then
update wflow.bpm_org_jobusers set userid = 0 where :OLD.user_id =userid and parentid=-1;
delete from wflow.bpm_org_jobusers where userid = :OLD.user_id;
delete wflow.bpm_org_user where userid=:OLD.user_id;
end if;
commit;
end;
:NEW 和:OLD使用方法和意义,new 只出现在insert和update时,old只出现在update和delete时。在insert时new表示新插入的行数据,update时new 表示要替换的新数据、old表示要被更改的原来的数据行,delete时old表示要被删除的数据。
注意:
在触发器中不能使用commit。