Oracle 學習筆記 18 -- 儲存函數和預存程序(PL/SQL子程式)

來源:互聯網
上載者:User

標籤:

PL/SQL子程式 它包含了函數和過程。此功能是指使用者定義的函數。和系統功能是不同的。子程式通常完成特定的功能PL/SQL座。,能夠被不同的應用程式多次調用。Oracle提供能夠把PL/SQL程式儲存在資料庫中,並能夠再不論什麼地方來執行它。

這樣就叫做存儲過程或者是函數。

過程和函數的唯一差別就是函數總是向調用者返回資料。而過程則不返回數據。

函數

假設使用者要常常運行某些操作,而且須要返回特定的資料。那麼就能夠將這些操作構造成一個函數。

能夠使用SQL語句定義函數。

基本的文法:

create or replace function fun_name(argument [in | out | in out ]datatype  ...)
return datatype 
is | as
       -- 須要定義的變數 。記錄類型 。 遊標
begin
       --函數的運行體
exception
       --處理出現的異常
end ;

當中,return datatype , 是要返回資料的類型。IN參數標記表示傳遞給函數的值在函數運行中不改變;OUT標記表示一個值在函數進行計算並通過該參數傳遞給調用語句;IN OUT 標記表示傳遞給函數的值能夠變化並傳遞給調用語句。

例:定義一個返回hello 的函數

create or replace function hello
return varchar2 
is
begin
       return ‘Hello World‘;
end ;

運行 ,Function created ,函數建立成功。

函數的調用。與Oracle內建函數的調用同樣,能夠使用select hello from dual ;進行調用,也能夠使用PL/SQL語句進行調用 :

begin 

  dbms_output.put_line(hello);

end ;

例:建立帶參數的helloworld函數

create or replace function helloworld(str varchar2)
return varchar2
is
begin
       return ‘Hello‘ || ‘_‘ ||str ;
end ;

函數的調用要在函數名稱後面加上參數,即:select helloworld(‘World‘) from dual ;使用Pl/sql的調用除了加上參數外與上面同樣,不在贅述。

例:求一個部門中,員工的工資總數的函數

create or replace function get_sal(dept number)
return number 
is
       v_sum number(10) := 0 ;
       cursor sal_cursor is select sal from emp where deptno = dept ;
begin 
       for c in sal_cursor loop
           v_sum := v_sum + c.sal ;
       end loop ;
       return v_sum ;
end ;

預存程序

預存程序,能夠被多個應用程式調用。也能夠向預存程序傳遞參數。向預存程序傳回參數。

基本的文法

create or replace procedure pro_name(argument [in | out | in out ]datatype  ...) 
is | as
       -- 須要定義的變數 ,記錄類型 , 遊標
begin
       --函數的運行體
exception
       --處理出現的異常
end ;

例:使用預存程序。求部門的工資總和

create or replace procedure get_sal1(dept number ,sumsal out  number)
is
       cursor sal_cursor is select sal from emp where deptno = dept ;
begin 
       sumsal := 0 ;
       for c in sal_cursor loop
           sumsal := sumsal + c.sal ;
       end loop ;
       dbms_output.put_line(sumsal);
end ;

預存程序的調用:

declare 
  v_sum number(10) := 0 ;
begin 
  get_sal1(30 , v_sum);
end ;

調用格式:

CALL | EXCEUTE procedure_name(arg_list) ;

能夠使用show error 命令來提示原始碼的錯誤位置。

使用user_error 資料字典來查看各預存程序的錯誤位置。

刪除過程和函數

刪除過程

文法例如以下:

DROP PROCEDURE[USER.]procedure_name ;

刪除函數

文法例如以下:

DROP FUNCTION [USER.]function_name ;


著作權聲明:本文博主原創文章。部落格,未經同意不得轉載。

Oracle 學習筆記 18 -- 儲存函數和預存程序(PL/SQL子程式)

聯繫我們

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