文法規則: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。