Oracle动态游标

Oracle动态游标

(一)强类型动态游标
1 定义
强类型动态游标是指,在游标使用之前,虽未指定游标的查询定义,但是游标的类型已经确定。

2 语法
type 游标类型 is ref cursor return 记录类型

3 应用场景、
用户想在表dept中查看Beijing这一城市的具体信息。如果表中没有Beijing的记录信息,则用户希望能够查看所有城市的信息。

程序:
begin
  declare
  type ref_deptrow is ref cursor return dept%rowtype; /*强类型动态游标声明*/
  c_count number;
  deptrow dept%rowtype;
  cur_deptrow ref_deptrow;

  begin
    select count(*) into c_count from dept where loc = 'Beijing';
    if c_count = 0 then
      open cur_deptrow for select * from dept;
    else
      open cur_deptrow for select * from dept where loc = 'Beijing';
    end if;
 
    fetch cur_deptrow into deptrow;
    while cur_deptrow%found loop
      dbms_output.put_line(deptrow.deptno || ':' || deptrow.dname || ':' || deptrow.loc);
      fetch cur_deptrow into deptrow;
    end loop;
  end;
 
end;
/

运行结果:
10:ACCOUNTING:NEW YORK
20:RESEARCH:DALLAS
30:SALES:CHICAGO
40:OPERATIONS:BOSTON

PL/SQL procedure successfully completed.


(三)弱类型动态游标
1 定义
弱类型动态游标指的是在游标使用之前,游标的类型无法具体确定,要等到程序执行时,才能确定游标的类型。与强类型动态游标相比,弱类型动态游标没有返回类型。

2 语法
type 游标类型 is ref cursor

3 应用场景
用户想要在表emp查询deptno为40的部门信息,若查不到则想在表dept中继续查询。
程序:
begin
  declare
  type ref_tablerow is ref cursor;      
  c_count number;    
  emprow emp%rowtype;                             
  deptrow dept%rowtype;             
  cur_tablerow ref_tablerow;
 
  begin
    select count(*) into c_count from emp where deptno = 40;

    if c_count = 0 then
      open cur_tablerow for select * from dept where deptno = 40;
      fetch cur_tablerow into deptrow;
      while cur_tablerow%found loop
        dbms_output.put_line(deptrow.deptno || ':' ||
                 deptrow.dname || ':' ||
                 deptrow.loc);
        fetch cur_tablerow into deptrow;
      end loop;
    else
      open cur_tablerow for select * from emp where deptno = 40;
      fetch cur_tablerow into emprow;
      while cur_tablerow%found loop
        dbms_output.put_line(emprow.deptno || ':' ||
                 emprow.empno || ':' ||
                 emprow.ename);
        fetch cur_tablerow into deptrow;
      end loop;
    end if;

  end;

end;
/

运行结果:
40:OPERATIONS:BOSTON

PL/SQL procedure successfully completed.

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29485627/viewspace-1248672/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/29485627/viewspace-1248672/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值