码迷,mamicode.com
首页 > 数据库 > 详细

Oracle 包(package)

时间:2015-05-09 23:29:40      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:

1、
包是一组相关过程、函数、变量、常量#SinaEditor_Temp_FontName、类型和游标等PL/SQL程序设计元素的组合。包具有面向对象设计的特点,是对这些PL/SQL程序设计元素的封装。一个包由两个分开的部分组成:
 
(1)包package声明或定义:包定义部分是创建包的规范说明,声明包内数据类型、变量、常量、游标等元素。这部分也是为使用者提供了透明的接口。
 
(2)包体packpage body:包体是包定义部分的具体实现。
 
(3)将有联系的对象打成包,方便使用
 
(4)包中对象包括储存过程,函数,游标,自定义类型和变量,可以在PL_SQL块中应用这些对象.
 
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
        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;

 

 

只有当包头编辑成功后才能编辑包体,其中的函数名与过程名须和包头中的函数过程一样。
 
1 包说明和包体必须有相同的名字
 
2 包的开始没有begin语句,与存储过程和函数不同。
 
3 在包的说明部分定义函数和过程的名称和参数,具体实现在包体中定义。
 
4 在包内声明常量、变量、类型定义、异常、及游标时不使用declare。
 
5 包内的过程和函数的定义不要create or replace语句。
 
6 包声明和包体两者分离。

 

 

 (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;

 

Oracle 包(package)

标签:

原文地址:http://www.cnblogs.com/wakey/p/4491348.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!