Oracle动态游标
(一)强类型动态游标
1 定义
强类型动态游标是指,在游标使用之前,虽未指定游标的查询定义,但是游标的类型已经确定。
2 语法
type 游标类型 is ref cursor return 记录类型
3 应用场景、
用户想在表dept中查看Beijing这一城市的具体信息。如果表中没有Beijing的记录信息,则用户希望能够查看所有城市的信息。
程序:
begin
declare
type ref_deptrow is ref cursor return dept%rowtype; /*强类型动态游标声明*/
c_count number;
deptrow dept%rowtype;
cur_deptrow ref_deptrow;
begin
select count(*) into c_count from dept where loc = 'Beijing';
if c_count = 0 then
open cur_deptrow for select * from dept;
else
open cur_deptrow for select * from dept where loc = 'Beijing';
end if;
fetch cur_deptrow into deptrow;
while cur_deptrow%found loop
dbms_output.put_line(deptrow.deptno || ':' || deptrow.dname || ':' || deptrow.loc);
fetch cur_deptrow into deptrow;
end loop;
end;
end;
/
运行结果:
10:ACCOUNTING:NEW YORK
20:RESEARCH:DALLAS
30:SALES:CHICAGO
40:OPERATIONS:BOSTON
PL/SQL procedure successfully completed.
(三)弱类型动态游标
1 定义
弱类型动态游标指的是在游标使用之前,游标的类型无法具体确定,要等到程序执行时,才能确定游标的类型。与强类型动态游标相比,弱类型动态游标没有返回类型。
2 语法
type 游标类型 is ref cursor
3 应用场景
用户想要在表emp查询deptno为40的部门信息,若查不到则想在表dept中继续查询。
程序:
begin
declare
type ref_tablerow is ref cursor;
c_count number;
emprow emp%rowtype;
deptrow dept%rowtype;
cur_tablerow ref_tablerow;
begin
select count(*) into c_count from emp where deptno = 40;
if c_count = 0 then
open cur_tablerow for select * from dept where deptno = 40;
fetch cur_tablerow into deptrow;
while cur_tablerow%found loop
dbms_output.put_line(deptrow.deptno || ':' ||
deptrow.dname || ':' ||
deptrow.loc);
fetch cur_tablerow into deptrow;
end loop;
else
open cur_tablerow for select * from emp where deptno = 40;
fetch cur_tablerow into emprow;
while cur_tablerow%found loop
dbms_output.put_line(emprow.deptno || ':' ||
emprow.empno || ':' ||
emprow.ename);
fetch cur_tablerow into deptrow;
end loop;
end if;
end;
end;
/
运行结果:
40:OPERATIONS:BOSTON
PL/SQL procedure successfully completed.
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29485627/viewspace-1248672/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/29485627/viewspace-1248672/