for 循环中的引用游标

ref cursor in for loop

ref cursor可以像游标一样用在for循环中吗?即像

for i in cur_name 
loop
dbms_output.put_line(i.column_name)
end loop; 

如果不可能那么为什么?

您不能像针对 implicit/explicit cursors

那样使用 for 循环
declare
    ref_cur sys_refcursor;
BEGIN
    OPEN ref_cur FOR SELECT table_name FROM all_tables WHERE ROWNUM < 5;
    for i in ref_cur loop
        dbms_output.put_line(i.table_name); 
    end loop;  
END;
/

你会得到一个错误

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

A ref cursor 是指向 open cursor 的指针,用于将打开的游标作为输出参数发送到客户端应用程序以循环记录。
如果要循环的话,

declare
    ref_cur sys_refcursor;
    v_name all_tables.table_name%TYPE;
BEGIN
    OPEN ref_cur FOR SELECT table_name FROM all_tables WHERE ROWNUM < 5;
    LOOP
        FETCH  ref_cur INTO  v_name;
        exit when ref_cur%notfound;
        dbms_output.put_line(v_name); 
    end loop;  
END;
/

如果游标的生命周期在*block*

,你可以使用implicit/explicit cursors
declare
    cursor cur IS SELECT table_name FROM all_tables WHERE ROWNUM < 5;
BEGIN 
    for i in cur loop
        dbms_output.put_line(i.table_name); 
    end loop;
END;
/

BEGIN 
    for i in (SELECT table_name FROM all_tables WHERE ROWNUM < 5) loop
        dbms_output.put_line(i.table_name); 
    end loop;
END;
/