游标分类:
静态游标:显式游标和隐式游标称为静态游标,因为在使用他们之前,游标的定义已经完成,不能再更改。
动态游标:游标在声明时没有设定,在打开时可以对其进行修改。分为强类型游标和弱类型游标。 强类型动态游标:在声明变量时使用return关键字定义游标的返回类型 。弱类型动态游标:在声明变量时不使用return关键字定义游标的返回类型
一般动态游标有 REF CURSOR(弱类型)、REF CURSOR RETURN(强类型)、SYS_REFCURSOR(弱类型)。
动态游标(强类型)
declare
--定义强类型 ,返回的类型与定义的类型v_dept必须一致
type c_dept_ref is ref cursor return dept%rowtype;
cur_dept c_dept_ref;
v_dept dept%rowtype;
begin
open cur_dept for select * from dept;
--动态游标,不能使用for循环
loop
fetch cur_dept into v_dept;
exit when cur_dept%notfound ;
dbms_output.put_line(v_dept.dname);
end loop;
close cur_dept;
end;
动态游标(弱类型)
--弱类型
declare
type c_cursor is ref cursor;
v_ref_cur c_cursor;
v_emprow emp%rowtype;
v_deptrow dept%rowtype;
begin
open v_ref_cur for
select * from dept;
loop
fetch v_ref_cur
into v_deptrow;
exit when v_ref_cur%notfound;
dbms_output.put_line(v_deptrow.dname);
end loop;
close v_ref_cur;
dbms_output.put_line('-------------------------');
open v_ref_cur for
select * from emp where deptno = 10;
loop
fetch v_ref_cur
into v_emprow;
exit when v_ref_cur%notfound;
dbms_output.put_line(v_emprow.ename);
end loop;
close v_ref_cur;
exception
when others then
dbms_output.put_line(sqlerrm);
end;