存储过程和存储函数
指存储在数据库中供所有用户程序调用的
子程序叫存储过程、存储函数。
存储过程和存储函数的区别?
存储函数:可以通过return 语句返回函数值。
存储过程:不能
除此之外我们可以认为他们是完全一样的。
存储过程
创建存储过程
用create procedure命令简历存储过程。
语法:
create [or replace] procedure 过程名(参数列表)
as
PLSQL子程序体;
打印hello word
--打印hello world create or replace procedure sayhelloworld as --说明部分 begin dbms_output.put_line('hello world'); end; /编译后:
调用存储过程方法:
1、exec 过程名
2、begin
过程名;
过程名;
end;
/
测试调用存储过程
--连接数据库
C:\WINDOWS\system32>sqlplus scott/
[email protected]:1521/orcl
SQL>--调用方式一
SQL> set serveroutput on
SQL> exec sayhelloworld;
hello world
PL/SQL 过程已成功完成。
SQL> --调用方式二:
SQL> begin
2 sayhelloworld();
3 sayhelloworld();
4 end;
5 /
hello world
hello world
PL/SQL 过程已成功完成。
|
--给指定员工薪水涨100,并且打印涨前和涨后的薪水 create or replace procedure raiseSalary(eno in number) --in为输入参数 as --说明部分 psal emp.sal%type; begin --得到涨前的薪水 select sal into psal from emp where empno=eno; update emp set sal=sal+100 where empno=eno; --要不要commit? --为保证在同一事务中,commit由谁调用谁提交 dbms_output.put_line('涨前:'||psal||' 涨后:'||(psal+100)); end; /测试:
存储函数
函数(function)为一命名的存储程序,可带参数,并返回一计算值。函数和过程的结构类似,但必须有一个return子句,用于返回函数值。函数说明要指定函数名、结果值的类型,以及参数类型等。
存储函数语法:
create[or replace] functiion 函数名(参数列表)
return函数值类型
as
PLSQL子程序体;
查询员工年收入
--查询某个员工的年收入 create or replace function queryempincome(eno in number) return number as --月薪和奖金 psal emp.sal%type; pcomm emp.comm%type; begin select sal,comm into psal,pcomm from emp where empno=eno; --返回年收入 return psal*12+nvl(pcomm,0); end; /测试
过程和函数中的in 和out
一般来讲,过程和函数的区别在于函数可以有一个返回值;而过程没有返回值。
但过程和函数都可以通过out指定一个或多个输出参数,我们可以利用out参数,在过程和函数中实现返回多个值。
什么时候用存储过程/存储函数?
原则(不是必须的):
如果只有一个返回值,用存储函数;否则,就用存储过程。
存储过程
create or replace procedure queryEmpInfo(eno in number, pname out varchar2, psal out number, pjob out varchar2) as begin select ename,sal,empjob into pname,psal,pjob from emp where empno=eno; end;