- 存储过程/存储函数:指存储在数据库中供所有用户程序调用的子程序
存储过程和存储函数的相同点:完成特定功能的程序
存储过程和存储函数的区别:是否用return语句返回值
存储函数用return语句返回值,而存储过程不能 创建和使用存储过程
用CREATE PROCEDURE 命令建立存储过程和存储函数
语法:
create [ or replace ] PROCEDURE 过程名(参数列表)
AS
PLSQL 子程序体;
存储过程只能创建或替换,如果修改要使用replace
调用存储过程:
1.exec sayhelloworld();
2.begin
sayhelloworld();
commit;
end;练习:打印Hello World create or replace procedure sayhelloworld as --说明部分 begin dbms_output.put_line("Hello World"); end; 练习:创建一个带参数的存储过程 给指定的员工涨100块钱的工资,并且打印涨前和涨后的薪水 create or replace procedure raisesalary(eno in number) --in为输入参数,out为输出参数 as --定义一个变量保存涨前的薪水 psal emp.sal%type; begin --得到员工涨前的薪水 --into 将sal的值赋予psal select sal into psal from emp where empno = eno; --给该员工涨100 --注意:一般不在存储过程或者存储函数中,commit和rollback, 谁调用谁commit和rollback update emp set sal = sal+100 where empno = eno; --打印 dbms_output.put_line("涨前:"||psal||"涨后:"(psal+100)); end;
存储函数
函数(Function)为一命名的存储程序,可带参数,并返回一计算值。
函数和过程的结构类似,但必须有一个RETURN子句,用于返回函数值。- 创建存储函数
语法:
create [ or replace ] FUNCTION 函数名(参数列表)
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,
pename out varchar2,
psal out number,
pjob out varchar2)
as
begin
–得到该员工的姓名、月薪、职位
select ename,sal,empjob into pename,psal,pjob from emp where empno=eno;
end;
思考:1. out参数太多 2.out中返回集合在应用程序中访问存储过程和存储函数
调用存储过程:{call [(,,…)]}
调用存储函数:{?=call [(,,…)]}
eg:String sql = “{call queryempinfo(?,?,?,?)}”;
String sql = “{?=call quertempincon(?)}”;在out参数中使用光标
申明包结构:包头、包体。包头负责声明,包体负责实现。
案例:查询某个部门中所有员工的所有信息
包头:
CREATE OR REPLACE PACKAGE mypackage AS
type empcursor is ref cursor;–声明一个光标类型empcursor
procedure queryEmplist(dno in number,empList out empcursor);
END mypackage;包体: 包体需要实现包头中声明的所有方法 CREATE OR REPLACE PACKAGE BODY mypackage AS procedure queryEmpList(dno in number,empList out empcursor) AS BEGIN --光标使用前需要打开光标 open empList for select * from emp where deptno = dno; END queryEmpList; END mypackage;
在应用程序中访问包中的存储过程
注意:需要带上包名
调用存储过程:{call [(,,…)]}
eg:String sql = “{call mypackage.queryEmpList(?,?)}”;
ORACLE的存储过程和函数
最新推荐文章于 2020-09-09 17:25:44 发布