PL SQL For 循环 Sys_RefCursor

PL SQL For Loop Sys_RefCursor

我正在使用 Oracle 12c。在 PL/SQL 我可以做到

set serveroutput on
declare
begin
  for x in (select 1 as y from dual) loop
    dbms_output.put_line(x.y);
  end loop;
end;

这个我也可以...

set serveroutput on
declare
  cursor c1 is
    select 1 as y from dual;
begin
  for x in c1 loop
    dbms_output.put_line(x.y);
  end loop;
end;

到目前为止,还不错。但是我可以用 sys_refcursor 来做到这一点吗?我知道我可以用 fetch/while 循环来做,但更喜欢 for 循环语法(我认为它更简洁)...

set serveroutput on
declare
  cur sys_refcursor;
begin
  cur := Package.GetData(1234);
  fetch cur into y;
  while cur%FOUND loop
    dbms_output.put_line(y);
    fetch cur into y;
  end loop;
end;

我想做...

set serveroutput on
declare
  cur sys_refcursor;
begin
  cur := PACKAGE.GetData(1234); -- This returns a sys_refcursor
  for x in cur loop
    dbms_output.put_line(x.y);
  end loop;
end;

Error report -
ORA-06550: line 5, column 16:
PLS-00221: 'cur' is not a procedure or is undefined

是否有一种机制可以通过 sys_refcursor 循环(而不是 fetch into/while 循环)?也许 12c 中有一些我不知道的新奇事物...?

SYS_REFCURSOR 只是一个预先声明的弱引用游标。没有这种机制可以在不获取的情况下循环 sys_refcursor 。此外,您不能将弱 refcursor 与普通游标进行比较,它们的工作方式不同。它是一个缓冲区 space ,分配用于临时保存结果。当您 运行 PLSQL 块中的以下语句时,PLSQL 引擎不理解它是一个 PLSQL 变量并抛出错误

for x in cur loop

PLS-00221: 'CUR' is not a procedure or is undefined

除此之外,下面的语句也会失败,因为您没有为包定义 OUT 参数,如果它返回 运行 一个 SYS_REFCURSOR

cur := PACKAGE.GetData(1234);

您可以获取SYS_REFCURSOR的内容,然后显示如下:

declare
  a  SYS_REFCURSOR;
  v_emp_id  employee.emp_id%type;
begin         
  --- This is a procedure with OUT parameter as SYS_REFCURSOR
  dynmc_selec(emp_output=>a);

  loop
    FETCH a INTO v_emp_id;
    EXIT WHEN a%NOTFOUND;
    DBMS_OUTPUT.PUT_LINE(v_emp_id );

  end loop;
end;