1、语法
create or replace function 函数名(参数1 in|out 类型,参数2 in|out 类型) retrun 结果类型
as|is
--定义变量
begin
return 变量;--(变量的类型一定是跟 return的结果类型保持一致)
end; 2、应用
(1)声明fun_emp_totalsal存储函数,查询指定员工的年薪
create or replace function fun_emp_totalsal(eno number) return number
as
psal number;
begin
select sal*12+nvl(comm,0) into psal from emp where empno = eno;
return psal;
end;
调用:
declare
totalSal number;
begin
totalSal := fun_emp_totalsal(7788);
dbms_output.put_line(totalSal);
end;
运行:
(2)声明pro_emp_totalsal存储过程,查询指定员工的年薪
create or replace procedure pro_emp_totalsal(eno number,totalsal out number)
as
begin
select sal*12+nvl(comm,0) into totalsal from emp where empno = eno;
end; 调用和运行和上面的存储函数一样。
(3)声明fun_emp_dname存储函数,根据部门编号查询出部门名称
create or replace function fun_emp_dname(dno number) return dept.dname%type
as
pname dept.dname%type;
begin
select dname into pname from dept where deptno = dno;
return pname;
end; 调用--查询编号为10的部门名称
declare
pname dept.dname%type;
begin
pname := fun_emp_dname(10);
dbms_output.put_line(pname);
end; (4)在select语句中调用存储函数
select empno,ename,fun_emp_dname(deptno) from emp;
3、存储过程和存储函数的区别:
- 语法不一样
- 存储函数必须有返回值
- 存储过程虽然没有返回值,但是可以指定输出参数类型
- 存储函数可以在select中使用