1. 程式人生 > >Oracle遊標的使用示例

Oracle遊標的使用示例

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