Oracle之函數與觸發器

來源:互聯網
上載者:User
 資料庫中函數包含四個部分: 聲明、傳回值、函數體和異常處理

 1 create or replace function getname(sno varchar2)
 2  return varchar is
 3         name varchar(12);
 4  begin
 5         select ename into name from emp where empno=sno;
 6         return name;
 7  exception
 8        ...
12  end;
13 

   觸發器是一種特殊的預存程序,類似於其它程式設計語言中的事件函數,允許為 INSERT、UPDATE、DELETE 建立觸發器,當在表(視圖)中插入、更新、刪除記錄(前、後)時,觸發一個或一系列 T-SQL 陳述式。

    建立在STUDENT表上的插入觸發器,當在STUDENT表中插入資料時候觸發器將被觸發,執行體將被執行

   插入觸發器
 1 create or replace trigger tg_insert
 2  before insert on student                --可設定在插入前或插入後
 3  begin
 4        ...
 5  end;
 

   更新觸發器
 8  create or replace trigger tg_update
 9  after update on student
10  for each row
12  begin
13      ...
14  END;
15 

觸發器兩個特殊行級變數: :New新值  和  :Old舊值  分別代表更新值,被更新的值

 1 create or replace trigger tg_insert
 2 after update on student
 3 for each row
 4 when (:old.sex=’j’)        --當old.sex為J時候才執行觸發器內容
 5 begin
 7    DBMS_OUTPUT.PUT_LINE(:new.stuname||'  '||:old.stuname);
 8    DBMS_OUTPUT.PUT_LINE(:new.sex||'  '||:old.sex);
 9 end;
10 

判斷複合型觸發器

 1 create or replace trigger trgstudeng
 2 before insert or update or delete on student
 3 for each row
 4 begin
 5     if  inserting then
 6     ...
 8     end if;
 9     if deleting then
10     ...
12     end if;
13 exception
14     ...
16 END;
17 

   觸發器功能強大,可以實現許多複雜的功能,但如果濫用會造成資料庫及應用程式的維護困難。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.