关于oracle中动态游标的使用例子ref cursor

本文介绍如何在Oracle数据库中使用REF Cursor实现动态SQL查询。首先创建包含学生信息的测试表,接着通过PL/SQL包定义REF Cursor类型,并实现根据ID获取学生信息的功能。最后,通过PL/SQL块演示如何调用此功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1、建立测试表  
  CREATE   TABLE   student  
    (  
      id                NUMBER,  
      name         VARCHAR2(30),  
      sex             VARCHAR2(10),  
      address     VARCHAR2(100),  
      postcode   VARCHAR2(10),  
      birthday     DATE,  
      photo        LONG   RAW  
    );  
  / 

 2、建立带ref   cursor定义的包和包体及函数:  

---------创建包头
  CREATE   OR   REPLACE  
  package   pkg_test   as  
  /*   定义ref   cursor类型  
        不加return类型,为弱类型,允许动态sql查询,  
        否则为强类型,无法使用动态sql查询;  
  */  
      type   myrctype   is   ref   cursor;    
     
  --函数申明  
      function   get(intID   number)   return   myrctype;  
      end   pkg_test;  
  /   
 

------------------------创建包体
  CREATE   OR   REPLACE  
  package   body   pkg_test   as  
  --函数体  
        function   get(intID   number)   return   myrctype   is  
            rc   myrctype;     --定义ref   cursor变量  
            sqlstr   varchar2(500);  
        begin  
            if   intID=0   then  
                  --静态测试,直接用select语句直接返回结果  
                  open   rc   for   select   id,name,sex,address,postcode,birthday   from   student;  
            else  
                  --动态sql赋值,用:w_id来申明该变量从外部获得  
                  sqlstr   :=   'select   id,name,sex,address,postcode,birthday   from   student   where  

id=:w_id';  
                  --动态测试,用sqlstr字符串返回结果,用using关键词传递参数  
                  open   rc   for   sqlstr   using   intid;  
            end   if;  
     
            return   rc;  
        end   get;  
     
  end   pkg_test;  
  /  
     
  3、用pl/sql块进行测试:  
  declare  
      w_rc               pkg_test.myrctype;   --定义ref   cursor型变量  
     
      --定义临时变量,用于显示结果  
      w_id               student.id%type;  
      w_name           student.name%type;  
      w_sex             student.sex%type;  
      w_address     student.address%type;  
      w_postcode   student.postcode%type;  
      w_birthday   student.birthday%type;  
     
  begin  
      --调用函数,获得记录集  
      w_rc   :=   pkg_test.get(1);  
     
      --fetch结果并显示  
    loop  
    fetch   w_rc   into   w_id,w_name,w_sex,w_address,w_postcode,w_birthday;  
    exit   when   w_rc%notfound;  
    dbms_output.put_line(w_name);  
    end   loop;  
  end;  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值