最近,在项目开发过程中,通过在存储过程、函数、包的使用过程,对游标有了一定的认识,所以,总结下来。
首先,举一个简单的例子,来比较一些通过 For..Loop 读取游标和 Open..Close 的区别。
-- declare
   -- this cursor is get table employee's info
cursor   cur_employee   is
       select  *   from   employee;

         -- this curso is get table dept's info
cursor   cur_dept   is
       select  *   from   dept;

         -- this cursor is get table employee & dept  info
cursor  cur_info  is
       select  e.*,   d.dept_name
    from  employee e ,  dept d
    where  e.dept_no  =  d.dept_no(+);

        -- to save cursor record's value
v_employee_row employee%rowtype;
v_dept_row dept%rowtype;
 
-- for .. loop
for v_row in cur_employee loop
   -- TODO-A
end loop;
   -- TODO-B
 
-- open ..close
open cur_employee
    fetch cur_employee into v_employee_row;
close cur_table_test;
 
      1.使用For..Loop的方式读取cursor,open、fetch、close都是隐式打开的。所以,不用担心忘记关闭游标而造成性能上的问题。
     2.使用For..Loop的代码,代码更加干净、简洁,而且,效率更高。
     3.使用For..Loop读取游标后,存储记录的变量不需要定义,而且,可以自动匹配类型。假如读取多个表的记录,显然用Open的fetch..into就显得相当困难了。
      fetch cur_info into X (这里的就相当麻烦,而且,随着涉及的表、字段的增加更加困难)    
     4.For..Loop在使用游标的属性也有麻烦的地方。因为记录是在循环内隐含定义的,所以,不能在循环之外查看游标属性。
         假如要做这样的处理:当游标为空时,抛出异常。把下面的读取游标属性的代码:
if   cur_employee%notfound  then
   -- can not found record form cursor
    RAISE_APPLICATION_ERROR(error_code, error_content);
end if;
放在 << TODO-B >> 的位置,虽然编译可以通过,但在运行时,就会报错: ORA-01001:invalid cursor
放在 << TODO-A>> 的位置,读取游标的 notfound 属性。显然,也是不行的。因为,如果游标为空的话,就会直接跳出循环,根本不会执行循环体内的代码。但是,也并不是说,就不能使用 For..Loop 来处理了。可以通过设置标志字段处理。
定义变量: v_not_contain_data bollean default true;
For..Loop 循环内增加一行代码: v_not_contain_data := false;
这样,在循环体外可以通过标志位来判断:
         If v_not_contain_data then
     RAISE_APPLICATION_ERROR(error_code, error_content);
end if;