PL/SQL程式之觸發器

來源:互聯網
上載者:User
觸發器1、資料庫觸發器是一個與表相關聯的、儲存的PL/SQL程式。每當一個特定的資料動作陳述式(Insert,update,delete)在指定的表上發出時,Oracle自動地執行觸發器中定義的語句序列。2、觸發器的類型1)、語句級觸發器在指定的動作陳述式操作之前或之後執行一次,不管這條語句影響了多少行 。2)、行級觸發器(FOR EACH ROW)觸發語句作用的每一條記錄都被觸發。在行級觸發器中使用old和new偽記錄變數, 識別值的狀態。建立觸發器:   CREATE  [or REPLACE] TRIGGER  觸發器名   {BEFORE | AFTER}   {DELETE | INSERT | UPDATE [OF 列名]}   ON  表名   [FOR EACH ROW [WHEN(條件) ] ]   PLSQL 塊執行個體一:限制非工作時間向資料庫中插入資料構建觸發器:create or replace trigger insertEmp  before insert on emp    for each rowdeclare  -- local variables herebegin  if to_char(sysdate,'day') in ('星期六') or to_number(to_char(sysdate,'hh24')) between 8 and 24    then       raise_application_error(-20001,'星期六或者8-24不能插入資料');      end if;end insertEmp;寫sql語句觸發SQL> insert into emp(empno,deptno) values (1245,10);結果:insert into emp(empno,deptno) values (1245,10)ORA-20001: 星期六或者8-24不能插入資料ORA-06512: 在 "SCOTT.INSERTEMP", line 6ORA-04088: 觸發器 'SCOTT.INSERTEMP' 執行過程中出錯觸發語句與偽記錄變數的值觸發語句     :old                        :newInsert所有欄位都是空話(null)將要插入的資料Update      更新以前該行的值            更新後的值Delete       刪除以前改行的值            所有欄位都是空(null)執行個體二:確認資料(檢查emp表中sal的修改值不低於原值)構建觸發器create or replace trigger updateEmp  before update on emp    for each rowdeclare  -- local variables herebegin  if :new.sal<:old.sal then    raise_application_error(-20002,'更改的資料不能小於原有的值');    end if;end updateEmp;書寫sql語句觸發SQL> update emp set sal=100 where empno=7369;結果:update emp set sal=100 where empno=7369ORA-20002: 更改的資料不能小於原原有的值ORA-06512: 在 "SCOTT.UPDATEEMP", line 5ORA-04088: 觸發器 'SCOTT.UPDATEEMP' 執行過程中出錯練習:限制每個部門只招聘5名職工,超過計劃則報出錯誤報表構建觸發器create or replace trigger insertEmp  before insert on emp    for each rowdeclare  -- local variables here  cursor c1 is select count(*) from emp group by deptno;  count1 number;begin  open c1;  fetch c1 into count1;   if      count1>=5   then     raise_application_error(-20003,'本部門不能再插入了');   end if;      --  dbms_output.put_line(count1);    close c1;end insertEmp;書寫sql語句觸發:SQL> insert into emp (empno,deptno) values(2435,30);結果:insert into emp (empno,deptno) values(2435,30)ORA-20003: 本部門不能再插入了ORA-06512: 在 "SCOTT.INSERTEMP", line 11ORA-04088: 觸發器 'SCOTT.INSERTEMP' 執行過程中出錯觸發器總結:1、觸發器可用於a)資料確認  b)實施複雜的安全性檢查c)   做審計,跟蹤表上所做的資料操作等2、查詢觸發器、過程及函數a)Select * from user_triggers;b)Select * from user_source;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.