服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > 数据库技术 > Oracle技术 > Oracle开发 > 查看文档

for loop读取游标和open close的区别

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

扫描关注微信公众号