標籤:oracle
什麼是觸發器【Trigger】?
不同的DML(select/update/delete/insert)操作,觸發器能夠進行一定的攔截,合格操作方可操作基表;反之,不可操作基表。類似於JavaWeb中的Filter、Struts2中的Iterceptor。
為什麼要用觸發器?
如果沒有觸發器,那麼DML所有操作,均可無限制地操作基表,這樣一來,不符合業務需求。
建立語句級觸發器insertEmpTrigger,當對錶【emp】進行增加【insert】操作前【before】,顯示"hello world"
create or replace trigger insertEmpTriggerbeforeinserton empbegin dbms_output.put_line(‘hello world‘); end;/
刪除觸發器insertEmpTrigger,文法:drop trigger 觸發器名
drop trigger insertEmpTrigger;
使用insert語句插入一條記錄,引起insertEmpTrigger觸發器工作
insert into emp(empno,ename) values(1234,‘小明‘);
使用insert語句插入N條記錄,引起insertEmpTrigger觸發器工作
insert into emp select * from xxx_emp;
650) this.width=650;" src="http://s2.51cto.com/wyfs02/M02/87/26/wKiom1fVcQiAvf6oAACOLRqDZZY156.jpg" title="001.jpg" alt="wKiom1fVcQiAvf6oAACOLRqDZZY156.jpg" />
建立語句級觸發器deleteEmpTrigger,當對錶【emp】進行刪除【delete】操作後【after】,顯示"world hello"
create or replace trigger deleteEmpTriggerbeforedeleteon empbegin dbms_output.put_line(‘刪除資料‘); end;/
使用delete語句刪除一條記錄,引起deleteEmpTrigger觸發器工作
delete from emp where empno=7369;
使用delete語句刪除N條記錄,引起deleteEmpTrigger觸發器工作
delete from emp where 1=1;
650) this.width=650;" src="http://s2.51cto.com/wyfs02/M00/87/24/wKioL1fVct-RhKPaAABnMDLjAr8993.jpg" title="002.jpg" alt="wKioL1fVct-RhKPaAABnMDLjAr8993.jpg" />
星期一到星期五,且9-20點能向資料庫emp表插入資料,否則使用函數拋出異常,
文法:raise_application_error(‘-20000‘,‘例外原因‘)
create or replace trigger securityTriggerbeforeinserton empdeclare pday varchar2(20); phour number(2);begin select to_char(sysdate,‘day‘) into pday from dual; select to_char(sysdate,‘hh24‘) into phour from dual; if pday in (‘星期六‘,‘星期日‘) or phour not between 7 and 22 then raise_application_error(‘-20000‘,‘非工作時間,不能向emp表添加資料‘); end if;end;/
650) this.width=650;" src="http://s4.51cto.com/wyfs02/M00/87/26/wKiom1fVeRzxkAcsAADl-flxCOw958.jpg" title="003.jpg" alt="wKiom1fVeRzxkAcsAADl-flxCOw958.jpg" />
建立行級觸發器checkSalaryTrigger,漲後工資這一列,確保大於漲前工資,文法:for each row/:new.sal/:old.sal
create or replace trigger checkSalaryTriggerafterupdate of salon empfor each rowbegin if :new.sal <= :old.sal then raise_application_error(‘-20200‘,‘工資不能越長越低‘); end if;end;/
其中,需要注意的地方
(1)update of sal是對列的更新進行觸發
(2)for each row
(3):new和:old代表一行記錄
(4)raise_application_error中-20000和-20200之間允許開發人員自訂錯誤
650) this.width=650;" src="http://s2.51cto.com/wyfs02/M00/87/24/wKioL1fVfQ_wKKu2AACas9wrI2Y726.jpg" title="004.jpg" alt="wKioL1fVfQ_wKKu2AACas9wrI2Y726.jpg" />
刪除觸發器,表還在嗎?
基表還在;觸發器不會進資源回收筒,直接徹底刪除
將表丟到資源回收筒,觸發器還在嗎?
觸發器還在
當閃回表後,觸發器會在嗎?
在
徹底刪除表,觸發器會在嗎?
原來的觸發器也被刪除了
新的同樣的名字的表,是不是繼承原來的觸發器的
Oracle系列:(30)觸發器