游标(cursor)
可以使用游标获取查询返回的行。在通过查询将行检索到游标中后,可以一次从游标中取出一行。
1.步骤
使用游标遵循下面5个步骤:
步骤1:声明用于保存列值的变量
注意:这些变量必须与列的类型兼容。
例如:
declare
v_id test.id%TYPE;
v_type test.type%TYPE;
步骤2:声明游标
由游标名和希望执行的查询组成。
例如:
cursor v_test_cursor is
select id,type
from test;
步骤3:打开游标
open v_test_cursor;
步骤4:从游标中取得行
使用fetch:将列的值读取到在第1步声明的变量中。
例如:
将列的值读取到在第1步声明创建的v_id和v_type中。
fetch v_test_cursor
into v_id,v_type
步骤5:关闭游标
close v_test_cursor;
完整示例:
declare
v_id test.id%TYPE;
v_type test.type%TYPE;
cursor v_test_cursor is
select id,type
from test;
begin
open v_test_cursor;
loop
fetch v_test_cursor
into v_id,v_type;
exit when v_test_cursor%NOTFOUND;
dbms_output.put_line(v_id || v_type);
end loop;
close v_test_cursor;
end;
结果:
101
201
2.游标与for循环使用
for循环时,可以不显式的打开和关闭游标。for循环会自动执行这些操作。
例如:
declare
cursor v_test_cursor is
select id,type from test;
begin
for v_test in v_test_cursor loop
dbms_output.put_line(v_test.id || v_test.type);
end loop;
end;
结果:
101
201
3.OPEN-FOR语句
可以将游标分配给不同的查询,因此可以灵活的处理游标
declare
type t_test_cursor_1 is ref cursor
return test%ROWTYPE; --声明的ref cursor(指向游标的指针)类型名为
t_test_cursor t_test_cursor_1;
v_test test%ROWTYPE; --返回test表中各行的一列,v_test用来存储test表的各列。
begin
open t_test_cursor for --test表中的所有数据加载到t_test_cursor游标中
select * --这里也是要写成*号,如果是字段,就报错!不明白为么????
from test;
loop
fetch t_test_cursor into v_test;
exit when t_test_cursor%NOTFOUND; --确定何时结束,当不能读出行时,为true,是一个布尔类型
dbms_output.put_line(v_test.id || v_test.type);
end loop;
close t_test_cursor;
end;
结果:
101
201
4.无约束游标
具有具体的返回类型,为约束游标。
约束游标返回的类型必须与游标运行时返回的类型相匹配。
无约束游标没有返回类型。
declare
type t_cursor is ref cursor;
v_cursor t_cursor;
v_test test%ROWTYPE;
v_order order%ROWTYPE;
begin
open v_cursor for
select * from test;
loop
fetch v_cursor into v_test;
exit when v_cursor%NOTFOUND;
dbms_output.put_line(v_test.id || v_test.type);
end loop;
open v_cursor for
select * from order;
loop
fetch v_cursor into v_order;
exit when v_cursor%NOTFOUND;
dbms_output.put_line(v_order.id || ' ' ||v_order.status);
end loop;
close v_cursor;
end;
结果:
101
201
1 new