网管联盟 | 网管论坛 | 网管u家 | 网管博客 | 网管软件 | 网管求职 | 小游戏 | 网管搜索 | 网管原创 | 网管聚合 | 网管读摘 | 网管焦点 | 世界素材 | 会员投稿 | 会员中心 
中国网管联盟
Windows Linux Cisco 网络技术 数据库 黑客攻防 DotNet Java PHP 认证 新闻资讯 服务器 存储资讯 网络设备 网管学堂 技术专题 焦点 网吧频道
 当前位置: > bitsCN.com > 数据库技术 > Oracle > PL/SQL > PL/SQL - 嵌套游标 cursor-PLSQL  

PL/SQL - 嵌套游标 cursor-PLSQL

2008-07-04  作者:bitsCN整理  来源:中国网管联盟  点评 投稿 收藏

       cursor() 函数可以将一个查询结果集封装成一个类似 REF CURSOR 的游标变量,可以 FETCH 记录,也可以作为 REF CURSOR 类型的参数进行传递。它被称为“嵌套游标(nested cursor)”。         1. FETCH 记录         我们先看一下测试表 test1 和 test2 的数据:  
SQL> select * from test1;            A
----------
         1
         1
         2
         3   SQL> select * from test2;           ID NAME
---------- ------------------------------------------

网管下载dl.bitscn.com


         1 yuechaotian1
         2 yuechaotian2
         3 yuechaotian3
         4 yuechaotian4
         5 yuechaotian5
    我们可能会发出这样一个查询:  
SQL> select id, name, (select a from test1 where a = test2.id)
  2    from test2;
select id, name, (select a from test1 where a = test2.id)
                  *
ERROR 位于第 1 行:
ORA-01427: 单行子查询返回多个行
    因为表 test1 中有两条 a=1 的记录,所以这个查询执行失败了。但有时候我们确实需要这样的查询,怎么办呢?你可以试试 cursor() 函数:  
SQL> set serveroutput on SQL> declare
网管bitscn_com

  2    cursor cur_test2 is
  3      select id, name, cursor(select a from test1 where a = test2.id)
  4        from test2;
  5    rec_test2 test2%rowtype;
  6
  7    cur_test1 sys_refcursor;
  8    rec_test1 test1%rowtype;
  9  begin
 10    open cur_test2;
 11    loop
 12      fetch cur_test2 into rec_test2.id, rec_test2.name, cur_test1;
 13      exit when cur_test2%notfound;
 14      dbms_output.put_line('rec_test2.id: ' || rec_test2.id || ' | rec_test2.name: ' || rec_test2.name);
 15      -- 这里不需要再显式 OPEN 游标 cur_test1,也不需要显式关闭
 16      loop
 17        fetch cur_test1 into rec_test1; 网管网www.bitscn.com
 18        exit when cur_test1%notfound;
 19        dbms_output.put_line( 'rec_test1.a: ' || rec_test1.a );
 20      end loop;
 21    end loop;  22    close cur_test2;
 23  end;
 24  /
rec_test2.id: 1 | rec_test2.name: yuechaotian1
rec_test1.a: 1
rec_test1.a: 1
rec_test2.id: 2 | rec_test2.name: yuechaotian2
rec_test1.a: 2
rec_test2.id: 3 | rec_test2.name: yuechaotian3
rec_test1.a: 3
rec_test2.id: 4 | rec_test2.name: yuechaotian4
rec_test2.id: 5 | rec_test2.name: yuechaotian5   PL/SQL 过程已成功完成。
 

 

网管下载dl.bitscn.com

 上一篇:Oracle数据库维护常用SQL语句集合(3)-PLSQL   下一篇:PL/SQL----触发器-PLSQL
PL/SQL - 嵌套游标 cursor-PLSQL 评论:
loading.. 评论加载中…
评论:请自觉遵守互联网相关政策法规,评论不得超过250字。

验证码: 注册用户
本类热门排行:
最新推荐文章:
网管论坛交流: