from https://www.cnblogs.com/1848/articles/1828927.html
數據庫中函數包含四個部分:聲明、返回值、函數體和異常處理。
無參函數
--沒有參數的函數 create or replace function get_user return varchar2 is v_user varchar2(50); begin select username into v_user from user_users; return v_user; end get_user; --測試 方法一 select get_user from dual; 方法二 SQL> var v_name varchar2(50) SQL> exec :v_name:=get_user; PL/SQL 過程已成功完成。 SQL> print v_name V_NAME ------------------------------ TEST 方法三 SQL> exec dbms_output.put_line('當前數據庫用戶是:'||get_user); 當前數據庫用戶是:TEST PL/SQL 過程已成功完成。
帶參函數
--帶有IN參數的函數 create or replace function get_empname(v_id in number) return varchar2 as v_name varchar2(50); begin select name into v_name from employee where id = v_id; return v_name; exception when no_data_found then raise_application_error(-20001, '你輸入的ID無效!'); end get_empname;
附:
函數調用限制
1、SQL語句中只能調用存儲函數(服務器端),而不能調用客戶端的函數
2、SQL只能調用帶有輸入參數,不能帶有輸出,輸入輸出函數
3、SQL不能使用PL/SQL的特有數據類型(boolean,table,record等)
4、SQL語句中調用的函數不能包含INSERT,UPDATE和DELETE語句
查看函數院源代碼
oracle會將函數名及其源代碼信息存放到數據字典中user_source
select text from user_source where name='GET_EMPNAME';
刪除函數
drop function get_empname;