10

Please, explain me how to use cursor for loop in oracle.

If I use next code, all is fine.

for rec in (select id, name from students) loop
    -- do anything
end loop;

But if I define variable for this sql statement, it doesn't work.

v_sql := 'select id, name from students';

for rec in v_sql loop
    -- do anything
end loop;

Error: PLS-00103

4 Answers 4

13

To address issues associated with the second approach in your question you need to use

cursor variable and explicit way of opening a cursor and fetching data. It is not

allowed to use cursor variables in the FOR loop:

declare
  l_sql varchar2(123);        -- variable that contains a query
  l_c   sys_refcursor;        -- cursor variable(weak cursor). 
  l_res your_table%rowtype;   -- variable containing fetching data  
begin
  l_sql := 'select * from your_table';

  -- Open the cursor and fetching data explicitly 
  -- in the LOOP.

  open l_c for l_sql;

  loop
    fetch l_c into l_res;
    exit when l_c%notfound;   -- Exit the loop if there is nothing to fetch.

     -- process fetched data 
  end loop;

  close l_c; -- close the cursor
end;

Find out more

Sign up to request clarification or add additional context in comments.

1 Comment

The most appropriate answer for now. I thought, that all will be easier. Thanks for your decision.
7

try this :

cursor v_sql is
select id, name from students;

for rec in v_sql 
loop
    -- do anything
end loop;

then no need to open, fetch or close the cursor.

2 Comments

I think, that this code will work if I will know sql code on stage of definition, but it generates on execution stage.
you can define parameters in the cursor definition, but only for the where clause. If you need to set the table dynamically, then the OPEN c FOR string is probably the way to go.
2

You're not executing that sql string anywhere. Simply do this

v_sql := 'select id, name from students';
open cur for v_sql;
for rec in cur loop
    -- do anything
end loop;

Or you can do this

cursor cur is select id, name from students;
open cur;
for rec in cur loop
        -- do anything
end loop;

Or you can do this

for rec in (select id, name from students) loop
    -- do anything
end loop

Comments

0

You have to use Refcursor if you are making the query at runtime. Actually refcursors are pointers to the query they wont take up any space for the rows fetched. Normal Cursors will not work for it.

declare 
v_sql varchar2(200);
rec sys_refcursor;
BEGIN
v_sql := 'select id, name from students';

open rec for v_sql 
loop
fetch
exit when....
-- do anything
end loop;

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.