此文是使用Oracle游标的几种方式,for...in会自动打开游标,fetch...into需要手动打开游标,游标类似于一个只会往前移动的指针,每次指向数据集中的一行数据,通过游标可以打开数据集,也能用于遍历数据集中的数据,在存储过程中可以实现loop循环,以及一些比较复杂的逻辑,也可以用于在存储过程中返回一个查询到的程序集。

create or replace procedure my_loop_cur_pro(presult out varchar) as
/*方法一,for in*/
/* pstring varchar(500);
begin*/
/*for in 是隐式打开关闭游标的,所以不需要定义一个游标*/
/* for pitem in (select * from emp) loop
begin
if pitem.DEPTNO = 20 then
pstring := pstring || ',' || pitem.ENAME;
end if;
end;
end loop;
presult:=pstring;
end;*/
 
/*方法二*/
/*使用 fetch into 的方式,这种方式必须手动的打开和关闭游标,同时必须在loop的时候明确的定义退出的条件,否则会出现死循环的现象*/
/* Cursor pcursor is
select * from emp;
pitem emp%rowtype; --%rowtype用于行类型%type用于列,字段,属性(eg emp.depno%type)
begin
open pcursor;
loop
fetch pcursor
into pitem;
exit when pcursor%notfound;--定义完成游标时退出
if pitem.Deptno = 20 then
presult := presult || pitem.ename;
end if;
end loop;
close pcursor;--必须手动关闭游标
end;*/
 
/*方法三*/
/*使用While遍历游标*/
/*cursor pcursor is
select * from emp;
pitem emp%rowtype;
begin
open pcursor;
fetch pcursor
into pitem; --while循环的时候,必须先Fetch一次游标,否则不会允许游标
while pcursor%found loop
--定义当游标获取到数据的时候循环
fetch pcursor
into pitem;
if pitem.deptno = 20 then
presult := presult || pitem.ename;
else
if pitem.deptno <> 20 then
presult := presult || ',';
end if;
end if;
end loop;
close pcursor;
end;
*/