3

Is ref cursor can be used in for loop like cursors? i.e. like

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

If not possible then why?

1

1 Answer 1

9

You can not use for loop just as you do against an implicit/explicit cursors

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;
/

you will get an error

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

A ref cursor being a pointer to an open cursor used to send an open cursor as an out argument to the client app to loop through the record.
If you want to loop through then,

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;
/

You can use implicit/explicit cursors if the life time of the cursor is with in the *block*

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;
/

or

BEGIN 
    for i in (SELECT table_name FROM all_tables WHERE ROWNUM < 5) loop
        dbms_output.put_line(i.table_name); 
    end loop;
END;
/
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.