一、用户自定义函数
1.语法
create or replace function 函数名
(参数1 参数类型 数据类型,参数2 参数类型 数据类型,...)
return 返回值的类型
is | as
声明变量 (不能加declare语句)
begin
...
return 返回值
...
exception
...
end;
2.参数类型
- 输入参数 in参数名
- 输出参数 out参数名
- 定义参数的时候,只能指定参数的数据类型,不能指定长度;
- 函数体至少要包含一条return语句。
例1 创建没有参数的函数
create or replace function fun_ShowTime return varchar2
is
begin
return to_char(sysdate,'YYYY-MM-DD HH24:MI');
end;
-
查看函数的编译错误,若无错误则创建成功
-
创建成功后,调用函数
select fun_ShowTime from dual;
-
查看函数的源代码
select text from user_source where name = 'FUN_SHOWTIME' order by line;
例2 创建带参数的函数
create or replace function fun_GetSname(inSno char) return varchar2 as vSname Student.Sname % type; begin select Sname into vSname from Studen where Sno = inSno; return vSname; exception when no_data_found then raise_application_error(-20001,'学号不存在'); end;
-
-
使用位置传递调用函数
select fun_GetSname('2017999') from dual;
-
使用名称传递调用函数
select fun_GetSname(inSno => '2017001') from dual;
例3 创建带输入输出参数的函数
create or replace function fun_GetStudent(inSno char,outSsex out varchar2) return varchar2 as vSname Student.Sname % type; begin select Sname,Ssex into vSname,outSsex from Student where Sno = inSno; return vSname; end;
-
调用函数
declare vSname Student.Sname % type; vSsex Student.Ssex % type; begin vSname := fun_GetStudent('2017002',vSsex); dbms_output.put_line('姓名:' || vSname || ',性别:' || vSsex); end;
-
删除函数