Oracle--包

  把之前独立的存储过程,函数 写在一起, 形成一个模块, 方便管理维护

包: 分为:

  1. 包的头部 函数,存储过程的声明,游标的声明
  2. 包的主体: 对函数,过程进行实现
  --包的头部的语法:
   create or replace package 包名
    is
       过程或函数的定义
       ….
    end;


  --注意: 同一个包, 包的头部的名字与包主体的名字一样
  --包的主体的语法:
   create or replace package body 包名
     is
        --对包的头部定义函数, 过程的实现
     
     end;

-- 包也是oracle对象, 保存在数据库中

例:

包的头部:

create or replace package mypkg 
 is
        procedure findSalByEmpno(v_no in emp.empno%type,v_sal out emp.sal%type);
        procedure findEmpByEmpno(v_no in emp.empno%type,empinfo out emp%rowtype);
        function findSalByEmpnoFun(v_no emp.empno%type) return emp.sal%type;
        function findEmpByEmpnoFun(v_no emp.empno%type) return emp%rowtype;
 end;

包的主体:

create or replace package body mypkg
is
   --对包的头部中定义的函数, 过程进行实现, 其实就是过程,函数完整写法
        procedure findSalByEmpno(v_no in emp.empno%type,v_sal out emp.sal%type)
          is    
          begin
            select sal into v_sal from emp where empno=v_no;
          end;

        procedure findEmpByEmpno(v_no in emp.empno%type,empinfo out emp%rowtype)
          is
             --静态的游标
              cursor emp_info is select * from emp where empno=v_no;
          begin
              open emp_info;
              fetch emp_info into empinfo;
              close emp_info;
          end;

        function findSalByEmpnoFun(v_no emp.empno%type) return emp.sal%type 
          is
                 v_sal emp.sal%type;
          begin
            select sal into v_sal from emp where empno=v_no;
            return v_sal;
          end;

        function findEmpByEmpnoFun(v_no emp.empno%type) return emp%rowtype 
          is
                 cursor emp_info is select * from emp where empno=v_no;
                 empinfo emp%rowtype;
          begin
                  open emp_info;
                  fetch emp_info into empinfo;
                  close emp_info;
                  return empinfo;
          end;
end;

执行:

--调用包中存储过程和函数     包名.存储过程名        包名.函数
--调用函数,  只能在PL/sql
declare
  v_emp emp%rowtype;
  V_sal emp.sal%type;
begin
   v_emp := MYPKG.FINDEMPBYEMPNOFUN(7788);
   v_sal := MYPKG.FINDSALBYEMPNOFUN(7788);
   dbms_output.put_line(v_emp.ename);
    dbms_output.put_line(v_sal);
end;

--select MYPKG.FINDSALBYEMPNOFUN(7788) from dual;
--调用存储过程
declare
  v_emp emp%rowtype;
  V_sal emp.sal%type;
begin
   MYPKG.FINDEMPBYEMPNO(7788,v_emp);
   MYPKG.FINDSALBYEMPNO(7788,V_sal);
   dbms_output.put_line(v_emp.ename);
    dbms_output.put_line(v_sal);
end;

猜你喜欢

转载自www.cnblogs.com/64Byte/p/12747076.html