Oracle遊標的使用
下面的例子完整說明遊標的聲明,開啟,提取關閉操作以及遊標參數的傳遞方法.
Declare
DeptRec dept%ROWTYPE;
dept_name dept.dname@TYPE;
dept_loc dept.loc%TYPE;
Cursor c1 Is
Select dname,loc from dept
where deptno<=30;
Cursor c2(dept_no number Default 10) is
select dname,loc
from dept
where deptno<=dept_no;
Cursor c3(dept_no Number Default 10)
Return dept%RowType
Is
Select * From Dept
where Deptno<=dept_no;
Begin
open c1;
open c2(30);
Loop
--迴圈提取c2遊標中的資料
Fetch c2 Into dept_name,dept_loc;
Exit When c2%NOTFOUND
DBMS_OUTPUT.PUT_LINE(DEpt_name ||''||Dept_loc);
End Loop;
Open c3(dept_no>=20);
Loop
--提取和處理c3遊標中的資料
Fetch c3 into DeptRec;
Exit When c3%NOTFOUND;
DBMS_OUTPUT.PUT_Line(DeptRec.deptno ||':'|| DeptRec.dname);
End Loop;
close c1;
close c2;
close c3;
End;
遊標For迴圈
Declare
Cursor c1(dept_no Number Default 10) Is
Select dname,loc From dept
where deptno<=dept_no;
Begin
Dbms_OutPut.PUT_LINE('dept_no值為30');
For c1_rec in c1(30) Loop
DBms_OUTPUT.PUT_LINE(c1_rec.dname ||':' || c1_rec.loc);
End Loop;
DBMS_OUTPUT.PUT_LINE(CHR(10) ||':'||使用預設值為10:');
For c1_rec in c1 Loop
DBms_OUTPUT.PUT_LINE(c1_rec.dname ||':' || c1_rec.loc);
End Loop
End;
此外,PL/SQL 還允許在For 迴圈中使用子查詢來實現遊標的功能.
Begin
For c1_rec In(select dname,loc From dept) Loop
Dbms_OutPUT.PUT_LINE(c1_rec.dname ||':' || c1_rec.loc);
end Loop;
end;
遊標屬性
%ISOPEN %FOUND %NOTFOUND %ROWCOUNT
聲明遊標變數
TYPE ref_type_name Is REF CURSOR [RETURN return_type]
例如:
Declare
TYPE DeptRecord Is Record
(
deptno dept.deptno%Type,
dname dept.dname%Type,
loc dept.loc%Type
);
Type DeptCurType Is Ref Cursor Return dept%ROWTYPE;
Type DeptCurTyp1 is Ref Cursor Return DeptRecord;
Type CurType Is Ref CurSor;
dept_c1 DeptCurType;
dept_c2 DeptCurTyp1;
cv CurType;
--------------------
定義動態變數和PL/SQL記錄
定義列類型的PL/SQL變數文法
variable_name table_name.column_name%TYPE;
定義一個具有與表中行相同的欄位的記錄
record_name table_name%ROWTYPE
定義一個具有與遊標中列相同的欄位的記錄
record_name cursor_name%ROWTYPE
PL/SQL記錄
TYPE record_type_name Is
(field_name1 field_1_type,
field_name2 field_2_tupe,
...
);