PL/SQL - 嵌套游标 cursor

来源:blog.chinaunix.net 作者:yuechaot… 2008-07-05 出处:pcdog.com

下一页 1 2 3 

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


更多内容请看PCdog.com--PL/SQL专题
下一页 1 2 3 
上一篇:SQL - 使用 Union 的注意事项
下一篇:log buffer及日志管理深入分析及性能调整