游标如果用open fetch 格式,当异常时可以写 close 游标
但是当游标用for 形式的时候,异常了 会自动关闭吗?
如 for idx in Test_Cursor loop
...
end loop当循环里出现异常抛到Exception的时候还用手动close掉Test_Cursor吗,
oracle会自动关闭吗?
谢谢

解决方案 »

  1.   


    --测试的例子
    SQL> declare
      2      cursor c1 is select ename from emp;
      3  begin
      4      for rec in c1 loop
      5          raise_application_error(-20001,'end loop');
      6      end loop;
      7   exception
      8   when others then
      9   if c1%isopen then
     10   dbms_output.put_line('open');
     11   else
     12   dbms_output.put_line('close');
     13   end if;
     14  end;
     15  /
    close                                                                           已順利完成 PL/SQL 程序.
      

  2.   

    如果是隐式打开的游标,不需要,也就是楼上兄弟给的例子。
    如果是显式打开,也就是open xxx,需要关闭。declare
      cursor c1 is select ename from emp;
      rec emp.ename%type;
    begin
      open c1;
      loop
        fetch c1 into rec;
        exit when c1%notfound;
        raise_application_error(-20001,'end loop');
      end loop;
      close c1;
    exception
      when others then
        if c1%isopen then
          dbms_output.put_line('open');
        else
          dbms_output.put_line('close');
        end if;
        close c1;
    end;结果输出
    open