此文是使用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;
*/