载自http://xiaoxinshome.javaeye.com/blog/139609
--------
语法规则:
Create [or replace] trigger [模式.]触发器名
Before| after insert|delete|(update of
列名)
On 表名
[for each row]
When 条件
PL/SQL块
说明:
For each row的意义是:在一次操作表的语句中,每操作成功一行就会触发一
次;不写的话,表示是表级触发器,则无论操作多少行,都只触发一次;
When条件的出现说明了,在DML操作的时候也许一定会触发触发器,但是触发器不一定会做实际的工作,比如when
后的条件不为真的时候,触发器只是简单地跳过了PL/SQL块;
例子:
sql 代码
- 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。