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;