SQL语句游标For.Loop与Open.Close比较

来源:互联网 发布:数据库access教程下载 编辑:程序博客网 时间:2024/05/16 07:33

转自:http://www.webjx.com/htmldata/2007-05-29/1180397791.html


在项目开发过程中,通过在存储过程、函数、包的使用过程,对游标有了一定的认识,总结如下。

首先,举一个简单的例子,来比较一些通过For..Loop读取游标和Open..Close的区别。

--declare--this cursor is get table employee's infocursor cur_employee isselect * from employee;--this cursor is get table dept's infocursor cur_dept isselect * from dept;--this cursor is get table employee & deptinfocursor cur_info isselect *,d.dept_namefrom employee , deptdwhere dept_no=d.dept_no(+);--to save cursor record's valuev_employee_row employee%rowtype;v_dept_row dept%rowtype;--for..loopfor v_row in cur_employee loop--TODO-Aend loop;--TODO-B--open..closeopen cur_employeefetch 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就显得相当困难了。

fetchcur_infointoX(这里的x就相当麻烦,而且,随着涉及的表、字段的增加更加困难)。

4.For..Loop在使用游标的属性,也有麻烦的地方。因为记录是在循环内隐含定义的,所以,不能在循环之外查看游标属性。

假如要做这样的处理:当游标为空时,抛出异常。

把下面的读取游标属性的代码:

if cur_employee%notfound then--can not found record form cursorRAISE_APPLICATION_ERROR(error_code,error_content);end if;


放在<>的位置,虽然编译可以通过,但在运行时,就会报错:ORA-01001:invalidcursor。

放在<>的位置,读取游标的notfound属性。显然,也是不行的。因为,如果游标为空的话,就会直接跳出循环,根本不会执行循环体内的代码。但是,也并不是说,就不能使用For..Loop来处理了。可以通过设置标志字段处理。

定义变量:v_not_contain_databolleandefaulttrue;

在For..Loop循环内增加一行代码:v_not_contain_data:=false;

这样,在循环体外可以通过标志位来判断:

If v_not_contain_data thenRAISE_APPLICATION_ERROR(error_code,error_content);end if;




原创粉丝点击