当前位置:Gxlcms > 数据库问题 > Oracle 包(Package)

Oracle 包(Package)

时间:2021-07-01 10:21:17 帮助过:3人阅读

定义包规范 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;

 

Oracle 包(Package)

标签:

人气教程排行