Oracle 包(Package)

引用这位大大的:

http://www.cnblogs.com/lovemoon714/archive/2012/02/29/2373695.html

1、为什么要使用包?

      答:在一个大型项目中,可能有很多模块,而每个模块又有自己的过程、函数等。而这些过程、函数默认是放在一起的(如在PL/SQL中,过程默认都是放在一起的,即Procedures中),这些非常不方便查询和维护,甚至会发生误删除的事件。所以通过使用包就可以分类管理过程和函数。
     而且在包中还可以自定义自定义类型,从而在过程和函数中可以直接使用自定义变量。Oracle中包的概念与JAVA中包的概念非常类似,只是JAVA中的包是为了分类管理类,但是关键字都是package。
     包分两部分,包规范包体

2、包的使用

(1)定义包规范,包规范可单独存在。

--定义包规范
create or replace package p_stu
as
    --定义结构体
    type re_stu is record(
        rname student.name%type,
        rage  student.age%type
    );
    --定义游标
    type c_stu is ref cursor;
    --定义函数
    function numAdd(num1 number,num2 number)return number;
    --定义过程
    procedure GetStuList(cid in varchar2,c_st out c_stu); 
end;

(2)实现包规范,即包体,名称必须一致,同样的游标定义不能出现,但结构体可以,方法、过程必须实现。

--实现包体,名称一致。
create or replace package body p_stu
as
    --游标和结构体,包规范中已声明,包体中不用再声明,直接使用。
    
    --实现方法   
    function numAdd(num1 number,num2 number)return number
    as
        num number;
    begin
        num:=num1+num2;
        return num;
    end;
    
    --实现过程
    procedure GetStuList(cid varchar2,c_st out c_stu)
    as
        r_stu re_stu; --直接使用包规范中的结构
    begin
      --打开游标并从select中取值
        open c_st for select name,age from student where classid=cid;
       -- 如果已经在过程中遍历了游标,在使用这个过程的块中,将没有值。
       -- loop
       --     fetch c_st into r_stu;  
       --     exit when c_st%notfound;
       --     dbms_output.put_line('姓名='||r_stu.rname);
       -- end loop;
    end;
end;

(3)使用

declare
    c_stu p_stu.c_stu;   --定义包中游标变量
    r_stu p_stu.re_stu;  --定义包中结构体变量
    num number;
begin
    --使用及遍历包中过程返回的结果集
    p_stu.GetStuList('C001',c_stu);
    loop
        fetch c_stu into r_stu;
        exit when c_stu%notfound;
        dbms_output.put_line('姓名='||r_stu.rname);
    end loop;
    
    --使用包中的方法
    select p_stu.numAdd(5,6) into num from dual;
    dbms_output.put_line('Num='||num);
end;
原文地址:https://www.cnblogs.com/xushining/p/5448879.html