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循环
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]
例如:
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,
...
);