Oracle中觸發器詳解 |
發布時間: 2012/5/31 15:08:11 |
Oracle觸發器分類: 1、 語句觸發器 2、 行觸發器 3、 系統條件觸發器 4、 用戶事件觸發器 5、 INSTEAD OF 觸發器 1、 語句觸發器 是在表上或者某些情況下的視圖上執行的特定語句或者語句組上的觸發器。能夠與INSERT、UPDATE、 DELETE或者組合上進行關聯。但是無論使用什么樣的組合,各個語句觸發器都只會針對指定語句激活一次 。比如,無論update多少行,也只會調用一次update語句觸發器。 例子: 需要對在表上進行DML操作的用戶進行安全檢查,看是否具有合適的特權。 Create table foo(a number); Create trigger biud_foo Before insert or update or delete On foo Begin If user not in (‘DONNY’) then Raise_application_error(-20001, ‘You don’t have access to modify this table.’); End if; End; / 即使SYS,SYSTEM用戶也不能修改foo表 [試驗] 對修改表的時間、人物進行日志記錄。 1、 建立試驗表 create table employees_copy as select *from hr.employees 2、 建立日志表 create table employees_log( who varchar2(30), when date); 3、 在employees_copy表上建立語句觸發器,在觸發器中填充employees_log 表。 Create or replace trigger biud_employee_copy Before insert or update or delete On employees_copy Begin Insert into employees_log( Who,when) Values( user, sysdate); End; / 4、 測試 update employees_copy set salary= salary*1.1; select *from employess_log; 5、 確定是哪個語句起作用? 即是INSERT/UPDATE/DELETE中的哪一個觸發了觸發器? 可以在觸發器中使用INSERTING / UPDATING / DELETING 條件謂詞,作判斷: begin if inserting then ----- elsif updating then ----- elsif deleting then ------ end if; end; if updating(‘COL1’) or updating(‘COL2’) then ------ end if; [試驗] 1、 修改日志表 alter table employees_log add (action varchar2(20)); 2、 修改觸發器,以便記錄語句類型。 Create or replace trigger biud_employee_copy Before insert or update or delete On employees_copy Declare L_action employees_log.action%type; Begin Oracle DBA if inserting then l_action:=’Insert’; elsif updating then l_action:=’Update’; elsif deleting then l_action:=’Delete’; else raise_application_error(-20001,’You should never ever get this error.’); Insert into employees_log( Who,action,when) Values( user, l_action,sysdate); End; / 3、 測試 insert into employees_copy( employee_id, last_name, email, hire_date, job_id) values(12345,’Chen’,’Donny@hotmail’,sysdate,12); select *from employees_log update employees_copy set salary=50000 where employee_id = 12345; 2、 行觸發器 是指為受到影響的各個行激活的觸發器,定義與語句觸發器類似,有以下兩個例外: 1、 定義語句中包含FOR EACH ROW子句 2、 在BEFORE……FOR EACH ROW觸發器中,用戶可以引用受到影響的行值。 3、 系統事件觸發器 系統事件:數據庫啟動、關閉,服務器錯誤 create trigger ad_startup after startup on database begin -- do some stuff end; / 4、 用戶事件觸發器 用戶事件:用戶登陸、注銷,CREATE / ALTER / DROP / ANALYZE / AUDIT / GRANT / REVOKE / RENAME / TRUNCATE / LOGOFF 本文出自:億恩科技【www.laynepeng.cn】 |