Oracle中的循环游标

Ant*_*ski 9 sql oracle plsql for-loop cursor

请解释一下如何在oracle中使用cursor for loop.

如果我使用下一个代码,一切都很好.

for rec in (select id, name from students) loop
    -- do anything
end loop;
Run Code Online (Sandbox Code Playgroud)

但是如果我为这个sql语句定义变量,它就不起作用.

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

for rec in v_sql loop
    -- do anything
end loop;
Run Code Online (Sandbox Code Playgroud)

错误:PLS-00103

Nic*_*nov 11

要解决与您的问题中的第二种方法相关的问题,您需要使用

游标变量和打开游标并获取数据的显式方式.它不是

允许在FOR循环中使用游标变量:

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;
Run Code Online (Sandbox Code Playgroud)

了解更多


小智 7

试试这个 :

cursor v_sql is
select id, name from students;

for rec in v_sql 
loop
    -- do anything
end loop;
Run Code Online (Sandbox Code Playgroud)

然后没有必要open,fetchclose光标.