oracle11g的程序包

版权声明:本文为博主原创,转载请附原文链接。 https://blog.csdn.net/bibibrave/article/details/82959655

程序包中的相关解释

程序包: 对 变量、函数、过程、游标、异常和对象的封装。
优点:把相关的内容放在一起。
程序包的组成:由包规范和包主体两部分组成。
规范(包头):公共对象的声明 变量、常量、异常、过程、函数、游标规范等等的声明。
主体(包体):私有对象的声明私有类型的声明以及包头内过程、函数的实现。

创建包头、包体的语法: body之分

包头 包体
CREATE [OR REPLACE] PACKAGE CREATE [OR REPLACE] PACKAGE BODY
package_name IS or AS package_name IS or AS
[Public item declarations] [Private item declarations]
END [package_name]; END [package_name];

公有对象:在包头内声明的变量,出了这个包还能使用。
私有对象:出了这个包我就不能使用了,仅仅我能用。

1、举例创建:

create or replace package  pack1 
 is 
   a int := 9 ;                          -- 公有变量
   procedure insert_student(a1  in student%rowtype );   --声明过程
   procedure update_student(a2  in student%rowtype );
 end pack1;
 /  
 create or replace package body pack1 
 is 
   b int := 6 ;                          -- 私有变量
   procedure insert_student(a1  in student%rowtype );   --过程定义1
   is
   begin
      insert into student(sno,sname,sage)  values (a1.sno ,a1.sname,a1.sage);
      commit;
      dbms_output.put_line(pack1.b);     --内部调用可以执行
   end  insert_student;
   procedure update_student(a2  in student%rowtype );   --过程定义2
    is
   begin
      update student set sname =a2.sname where sno=a2.sno ;
      commit;
   end  update_student;    
 end pack1;
 /

程序包的使用:
declare
  a1  student%rowtype ;
begin
  a1.sno:=1;
  a1.sname:='Jack';
  a1.sage:=20;
  pack1.insert_student(a1);
 end;
 /

判断变量范围:
execute  dbms_output.put_line(pack1.a);        --可以执行
execute  dbms_output.put_line(pack1.b);        --不可以执行

2、程序包的优点
在做项目的时候都是先建立程序包,再在程序包内建立相关过程与函数
模块化
更轻松的应用程序设计
信息隐藏
新增功能
性能更佳

3、在程序包中写游标
注意包头内声明游标、在包体中定义游标、在过程中使用游标的方法。

显示游标
 
 create or replace package pack2   -- 包头部分
 is
   cursor mycursor return student%rowtype;   -- 指明return
   procedure mycursor_use ;    -- 声明过程
  end pack2;
  /
 create or replace package body  pack2   --包体部分
 is
   cursor mycursor return student%rowtype is select * from student;   --注意statement
   procedure mycursor_use   
   is 
      stu_rec  student%rowtype;
      open mycursor;
      fetch mycursor into stu_rec;
      while mycursor%found loop
           dbms_output.putline('sno='||stu_rec.sno);
           fetch mycursor  into  stu_rec;
        end  loop;
        close mycursor;
    end mycursor_use;
  end pack2;
  /

exec pack2.mycursor_use;

猜你喜欢

转载自blog.csdn.net/bibibrave/article/details/82959655