Oracle之存储过程与存储函数

存储过程和存储函数指存储在数据库中供所有用户程序调用的子程序叫存储过程或者存储函数;
存储过程和存储函数
相同点:完成特定功能的任务;
不同点:是否用return语句返回值
存储过程不能通过return返回一个函数子句,存储函数通过return返回一个函数子句,引入Out函数后,存储函数可以用存储过程替代,存储函数只能有一个返回值,存储过程可以有多个返回值,因为要向下兼容,所以Oracle升级的时候保留了存储函数

create [or replace] procedure sayhelloworld
as
begin
  dbms_output.put_line('Hello_world');
end;
/

调用存储过程的方法:
第一种:

exec.sayhelloworld;

第二种:

begin 
  sayhelloworld;
  sayhelloworld;
end;
/

创建带参数的存储过程,如给指定的员工涨100元,并打印涨前和涨后的工资

create or replace procedure raisesalary(eno in number)
as psal emp.sal%type 
begin 
        select sal from emnp where empno=eno;
        update emp set sal=sal+100 where empno=eno;
        dbms_output.put_line('涨前:' ||psal||' '涨后:' ||cpsal+100));
end;
/

因为存储过程是子程序,所以内部的update操作不建议用commit和rollback;
创建存储函数的语句

create [or replace] function 函数名(参数列表)
return 函数值类型
as
PLSQL 子程序体

如存储函数->查询某个员工的年收入

create or replace function queryempincome(eno in number) //in代表输入参数
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;
/

out表示输出参数
如查询某个员工的姓名,月薪和职位

create or replace procedure queryempinform(eno in number, 
                                          pname out varchar2,
                                          psal out number,
                                          pjob out varchar2)
as 
begin
 select ename,sal,empjob into pename,psal,pjob from emp where empno=eno;
end;
/

创建JDBC的连接方式

driver;url;user,password;
Class.forName(driver);
driver.getConnection();
CallableStatement call = conn.prepareCall(sql);
call.setInt(1,7839);
call.registerOutParameter(2,OracleTypes.VARCHAR);
call.registerOutParameter(2,OracleTypes.NUMBER);
call.execute();
call.getDouble(3);
call.getString(4);

Out光标
创建包头

create or replace package mypackage as
        type empcursor is ref cusor;
        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;

参见https://www.imooc.com/learn/370

你可能感兴趣的:(Oracle之存储过程与存储函数)