首页 | 互联网 | IT动态 | IT培训 | Cisco | Windows | Linux | Java | .Net | Oracle | 软件测试 | C/C++ | 嵌入式开发 | 存储世界 | 服务器
网络设备 | IDC | 安全 | 求职招聘 | 数字网校 | 网页设计 | 平面设计 | 技术专题 | 电子书下载 | 教学视频 | 源码下载 | 搜索 | 博客 | 论坛
中国IT实验室Oracle频道
中国IT教育
Google
首页 入门基础 安装配置 体系架构 PLSQL 备份恢复 性能调优 开发技术 资讯动态 考试认证 下载 专题 讨论
您现在的位置: 中国IT实验室 >> Oracle >> PLSQL >> 正文

PL/SQL - 嵌套游标 cursor

        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
---------- ------------------------------------------
         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
  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;
 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 过程已成功完成。
 

[1] [2] [3] 下一页

【责编:michael】

中国IT教育

相关产品和培训
文章评论
 友情推荐链接
 认证培训
 社区讨论
 博客论点