1、存储过程、存储函数
概念:存储在数据库中供所有用户程序调用的子程序叫存储过程、存储函数。
相同点:存储过程和存储函数都是完成特定功能的子程序。
不同点:存储函数可以通过return返回值,存储过程不可以。
2、创建和使用存储过程
使用create procedure命令建立存储过程和存储函数。
语法:create (or replace) procedure 过程名(参数列表) AS pl/sql子程序体。
比如 一个hello world程序
Create (or replace) procedure sayHello
As
Begin
dbms_output.put_line(‘Hello world’);
end;
3、调用存储过程
1、Exec sayHello();
2、在另外一个pl/sql中调用
begin
sayHello();
end;
4、创建带参数的存储过程 给指定员工涨100元工资,并且打印涨前和涨后的工资
In关键字标识参数为输入参数
Create or replace procedure raisesalary (eno in number)
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?
--注意:一般不再存储过程和存储函数做提交和回滚,谁调用谁来提交和回滚
--打印信息
dbms_output.put_line(‘涨前:’||Psal||’ 涨后:’||(Psal+100));
End;
如何调用:begin
raisesalary(1233);
raisesalary(1523);
commit();
end;
5、创建存储函数的语法
Create or replace function函数名(参数列表)
Return 函数值类型
As
plSql程序体
查询某个员工的年收入:
Create or replace function querysalincome(eno in number)
Return number
As
--定义变量用于存放员工的薪水和奖金
Psal emp.sal%type
Pcom emp.income%type
Begin
Select sal into Psal,comm into Pcom from emp where empNo=eno;
Return Psal*12+nvl(Pcom,0);
End;
6、存储过程和存储函数都可以有out参数,存储过程可以通过out参数实现返回值。
Out参数-查询某个员工姓名、月薪和职位。
什么时候使用存储函数/存储过程?
如果只有一个返回值则使用存储函数,否则使用存储过程。
Create or replace procedure queryempinfo(eno in number,pname out varchar2,psal out number,pjob out varchar2)
As
Begin
--得到该员工的姓名 月薪和职位
Select sal,empName,job into pname,psal,pjob from emp where empno=eno;
End;
两个问题:
查询某个员工的所有信息 out参数如果太多就不能一一去写。
7、在应用程序中访问存储过程和存储函数 是使用CallableStatement接口
{call procedure_name(参数列表)}
对于输入参数需要复制 输出参数需要声明(使用CallableStatement的registerOutparameter方法),该方法带两个参数 第一个参数就是第几个占位符 第二个是该参数对应数据库的类型,调用OracleTypes指明就可以
取出out参数代表的值 使用 callablestatment对象.getString(?) 问号代表第几个占位符
8、在out参数中使用光标 例如:查询某个部门所有员工的信息
包头:create or replace package myPackage AS
type empcursor is ref cursor;
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;
9、在应用程序中访问包中的存储过程