Oracle中觸發(fā)器詳解 |
發(fā)布時間: 2012/5/31 15:08:11 |
Oracle觸發(fā)器分類: 1、 語句觸發(fā)器 2、 行觸發(fā)器 3、 系統(tǒng)條件觸發(fā)器 4、 用戶事件觸發(fā)器 5、 INSTEAD OF 觸發(fā)器 1、 語句觸發(fā)器 是在表上或者某些情況下的視圖上執(zhí)行的特定語句或者語句組上的觸發(fā)器。能夠與INSERT、UPDATE、 DELETE或者組合上進(jìn)行關(guān)聯(lián)。但是無論使用什么樣的組合,各個語句觸發(fā)器都只會針對指定語句激活一次 。比如,無論update多少行,也只會調(diào)用一次update語句觸發(fā)器。 例子: 需要對在表上進(jìn)行DML操作的用戶進(jìn)行安全檢查,看是否具有合適的特權(quán)。 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表 [試驗(yàn)] 對修改表的時間、人物進(jìn)行日志記錄。 1、 建立試驗(yàn)表 create table employees_copy as select *from hr.employees 2、 建立日志表 create table employees_log( who varchar2(30), when date); 3、 在employees_copy表上建立語句觸發(fā)器,在觸發(fā)器中填充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中的哪一個觸發(fā)了觸發(fā)器? 可以在觸發(fā)器中使用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; [試驗(yàn)] 1、 修改日志表 alter table employees_log add (action varchar2(20)); 2、 修改觸發(fā)器,以便記錄語句類型。 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、 行觸發(fā)器 是指為受到影響的各個行激活的觸發(fā)器,定義與語句觸發(fā)器類似,有以下兩個例外: 1、 定義語句中包含F(xiàn)OR EACH ROW子句 2、 在BEFORE……FOR EACH ROW觸發(fā)器中,用戶可以引用受到影響的行值。 3、 系統(tǒng)事件觸發(fā)器 系統(tǒng)事件:數(shù)據(jù)庫啟動、關(guān)閉,服務(wù)器錯誤 create trigger ad_startup after startup on database begin -- do some stuff end; / 4、 用戶事件觸發(fā)器 用戶事件:用戶登陸、注銷,CREATE / ALTER / DROP / ANALYZE / AUDIT / GRANT / REVOKE / RENAME / TRUNCATE / LOGOFF 本文出自:億恩科技【www.riomediacenter.com】 服務(wù)器租用/服務(wù)器托管中國五強(qiáng)!虛擬主機(jī)域名注冊頂級提供商!15年品質(zhì)保障!--億恩科技[ENKJ.COM] |