两种循环方式
一种使用游标,另一种使用for语句(for .. in (selec..) loop..)
问一下这种两种方式的优缺点有什么了??
开发中如何选择?

解决方案 »

  1.   

    以前的收藏:
    在实际的工作喝学习中,许多人对存储过程、函数、包的使用过程以及游标缺乏必要的认识,下文中,我们将通过一个简单的例子,比较一些通过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;