【问题标题】:Cursor for loop in OracleOracle 中的光标 for 循环
【发布时间】:2013-08-18 21:58:44
【问题描述】:

请解释一下如何在 oracle 中使用 cursor for 循环。

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

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

【问题讨论】:

    标签: sql oracle for-loop plsql database-cursor


    【解决方案1】:

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

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

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

    【讨论】:

    • 目前最合适的答案。我想,一切都会变得更容易。感谢您的决定。
    【解决方案2】:

    试试这个:

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

    那么就不需要openfetchclose光标了。

    【讨论】:

    • 我认为,如果我知道定义阶段的 sql 代码,这段代码就可以工作,但它会在执行阶段生成。
    • 您可以在游标定义中定义参数,但仅限于 where 子句。如果您需要动态设置表格,那么OPEN c FOR string 可能是要走的路。
    【解决方案3】:

    如果您在运行时进行查询,则必须使用 Refcursor。实际上,refcursors 是指向查询的指针,它们不会为获取的行占用任何空间。 普通光标不起作用。

    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;
    

    【讨论】:

      【解决方案4】:

      您没有在任何地方执行该 sql 字符串。只需这样做

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

      或者你可以这样做

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

      或者你可以这样做

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-03
        • 2013-03-29
        • 2021-03-02
        • 2020-06-26
        相关资源
        最近更新 更多