静态游标
显式游标和隐式游标称为静态游标,因为在使用他们之前,游标的定义已经完成,不能再更改。
动态游标
游标在声明时没有设定,在打开时可以对其进行修改。分为强类型游标和弱类型游标。
----------强类型动态游标:在声明变量时使用return关键字定义游标的返回类型
type cur_students_type is ref cursor return student_type;
cur_students cur_students_type ;
----------弱类型动态游标:在声明变量时不使用return关键字定义游标的返回类型
type cur_students_type is ref cursor;
cur_students cur_students_type ;
1 强类型动态游标
创建强类型游标:
传入学生年龄(in_age)
- 如果年龄小于0,则打印所有学生的信息。
- 反之,打印对应年龄的学生信息。
create or replace procedure printStudents(in_age in number) as
begin
declare
--自定义类型 student_type
type student_type is record(
id number,
name varchar2(10),
age number
);
begin
type cur_students_type is ref cursor return student_type; --type cur_students_type is ref cursor定义游标的类型
cur_students cur_students_type; --声明游标变量 --ref cursor表明是一个动态游标
student student_type; --声明变量 --return student_type表明是一个强类型游标
if in_age<=0 then
open cur_students for select * from tb_students;
else
open cur_students for select * from tb_students where student_age=in_age;
end if;
fetch cur_students into student;--获取游标中的结果集存储到student变量中
while cur_students%found loop --循环游标记录
dbms_output.put_line(student.id||'--'||student.name||'--'||student.age);--遍历输出记录
fetch cur_students into student;--游标指向下一个记录
end loop;
close cur_students ;
end;
end printStudents;
/
2 调用存储过程
- 年龄小于0
declare
begin
printStudents(-1);
end;
/
–结果:打印出全部学生信息
3 调用存储过程:
年龄等于20
declare
begin
printStudents(18);
end;
/
4 弱类型动态游标
创建弱类型游标:
传入参数in_flag
根据传入的参数判断打印学生表的何种信息。
create or replace procedure printStudentsByFlag(in_flag in varchar2) as
begin
declare
--自定义类型
type name_type is record(
id number,
name varchar2(10)
);
type age_type is record(
id number,
age varchar2(10)
);
--声明一个弱类型游标
type cur_students_type is ref cursor;
name name_type;
age age_type;
cur_students cur_students_type ; --声明变量
begin
if upper(in_flag)='NAME' then --打印姓名信息
open cur_students for
select student_id,student_name from students;
fetch students into name;
while cur_students%found loop
dbms_output.put_line(name.id||'--'||name.name);
fetch cur_students into name;
end loop;
elsif upper(in_flag)='AGE' then --打印年龄信息
open cur_students for
select student_id,student_age from students;
fetch cur_students into age;
while cur_students%found loop
dbms_output.put_line(age.id||'--'||age.age);
fetch cur_students into age;
end loop;
end if;
close cur_students;
end;
end printStudentsByFlag;
/
5 调用存储过程
- 传入NAME
declare
begin
printStudentsByFlag('NAME');
end;
/
6 调用存储过程
- 传入AGE
declare
begin
printStudentsByFlag('AGE');
end;
/