ORACLE 儲存函數

來源:互聯網
上載者:User

標籤:select   auth   指定   varchar   變化   end   過程   post   ret   

前奏:必要的概念:    ORACLE  提供能夠把 PL/SQL  程式儲存在資料庫中。並能夠在不論什麼地方來運行它。這樣就叫儲存過    程或函數。    過程和函數統稱為 PL/SQL 子程式。他們是被命名的 PL/SQL 塊,均儲存在資料庫中,並    通過輸入、輸出參數或輸入/輸出參數與其調用者交換資訊。過程和函數的唯一差別是函數總向調    用者返回資料。而過程則不返回資料。

1:建立函數CREATE [OR REPLACE] FUNCTION function_name[ (argment [ { IN | IN OUT }] Type,argment [ { IN | OUT | IN OUT } ] Type ][ AUTHID DEFINER | CURRENT_USER ]RETURN return_type { IS | AS }<類型.變數的說明> BEGINFUNCTION_bodyEXCEPTION其他語句END;2:說明:1) OR REPLACE 為可選. 有了它, 能夠或者建立一個新函數或者替換同樣名字的函數, 而不會出現衝突2) 函數名後面是一個可選的參數列表, 當中包括 IN, OUT 或 IN OUT 標記. 參數之間用逗號隔開. IN 參數標記表示傳遞給函數的值在該函數運行中不改變OUT 標記表示一個值在函數中進行計算並通過該參數傳遞給調用語句; IN OUT 標記表示傳遞給函數的值能夠變化並傳遞給調用語句. 若省略標記, 則參數隱含為 IN。3) 由於函數須要返回一個值, 所以 RETURN 包括返回結果的資料類型.3:例題:--儲存函數結構create function func_name(dept_id number , salary number)return numberis --函數使用過程中 須要聲明的變數 記錄類型 cursorbegin --函數的運行體exception --處理函數運行過程中異常end;--例題1 寫一個返回hellow world的functioncreate or replace function hello_func(temp varchar2)return varchar2isbegin return 'hello world'|| temp;end; --調用函數:begin dbms_output.put_line(hello_func);end;select hello_func('cui') from dual;--例二 寫一個返回系統時間的函數 假設函數沒有形參 切勿加()create function get_sysdatereturn dateisv_date date;beginv_date := sysdate;return v_date;end;select get_sysdate() from dual; --建立兩個參數相加的 儲存函數create function add_func(temp_A number , temp_B number)return numberistemp_sum number(10);begintemp_sum := temp_A + temp_B; return temp_sum;end;select add_func(1,1) from dual;--定義一個函數:擷取給定部門的工資總和。要求:部門號定義為參數,工資總額定義為傳回值;create function get_sal(dept_id number)return numberisv_sumsal number(10):=0;cursor salary_cursor is select salary from employees where department_id = dept_id;beginfor c in salary_cursor loop v_sumsal := v_sumsal + c.salary;end loop;return v_sumsal; end;select get_sal(60) from dual;--定義一個函數 擷取指定部門的工資總和 和 該部門的員工總數(定義為out類型的參數)--要求部門號定義為參數,工資總額定義為傳回值create function get_sall(dept_id number , total_count out number)return numberis v_sumsal number(10):=0;cursor salary_cursor is select salary from employees where department_id = dept_id;begintotal_count := 0;for c in salary_cursor loopv_sumsal := v_sumsal + c.salary;total_count := total_count + 1;end loop;return v_sumsal;end;4:函數的調用declare v_num number(5):=0;begin dbms_output.put_line(get_sall(60,v_num)); dbms_output.put_line(v_num);end;


ORACLE 儲存函數

聯繫我們

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