sql - Oracle中的游标循环

标签 sql oracle for-loop plsql cursor

请解释一下如何在oracle中使用游标进行循环。

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

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

但是,如果我为此sql语句定义变量,它将无法正常工作。
v_sql := 'select id, name from students';

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

错误:PLS-00103

最佳答案

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

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

允许在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;

Find out more

关于sql - Oracle中的游标循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18274258/

相关文章:

mysql - 使用来自同一列的数据计算百分比 SQL 语句

c# - int 与 datetime2 不兼容

sql - MySQL:左连接与右连接的联合

Oracle SQL Developer假脱机输出?

oracle - 随机化两个数据集

matlab - 每行中最大值元素的索引(最后一个索引)

SQL。如何正确组合子查询和连接?

sql - 如何使用 SQLPLUS 假脱机到 CSV 格式的文件?

javascript - 优化 for 循环,避免无用的查找

c - 如何正确使用有关字符串数组的 isalpha 函数?