一,什么是游标
遍历查询结果集的一种机制。
二,为什么避免使用游标
尽量避免使用游标, 因为游标的效率较差;
如果使用了游标,就要尽量避免在游标循环中再进行表连接的操作。
三,使用游标的步骤(静态游标)
1,声明一些变量,用来保存游标遍历过程的临时数据
2,声明游标,并且指定查询
3,打开游标
4,从游标中获取一行或多行记录
5,关闭游标
四,游标的属性
1,%isopen:是否打开游标
2,%rowcount:游标的行数
3,%found:是否还有数据
4,%notfound:是否没有数据
五,游标的分类(下面的分类不是并列关系)
1,静态游标:使用游标前就已经定义好,并且不能更改
2,动态游标:游标在声明时没有定义好,在打开时可以做更改
3,显示游标:使用游标前要声明、打开游标,使用完成需要关闭
4,隐示游标:事先没有声明打开游标,直接使用,也不需要关闭
5,强类型游标:声明游标时带return关键字,游标只能与特定的查询匹配
6,弱类型游标:声明游标时不带return关键字,游标可以与任意查询匹配
六,游标的具体使用栗子:
1,先创建表结构和插入数据
create table students(
id number,
name varchar2(10),
age number
);
insert into students values(1,'李白',18);
insert into students values(2,'妲己',16);
insert into students values(3,'赵信',20);
commit;
2,隐式游标
declare
begin
for student in(select * from students) loop
dbms_output.put_line('编号:'||student.id||',姓名:'||student.name||',年龄'||student.age);
end loop;
end;
3,显式游标
declare
cursor mycur is select * from students;
student students%rowtype;
begin
open mycur;
loop
fetch mycur into student;
exit when mycur%notfound;
dbms_output.put_line('编号:'||student.id||',姓名:'||student.name||',年龄'||student.age);
end loop;
close mycur;
end;
4,动态游标之强类型游标
--打印年龄小于18的学生
create or replace procedure printStudents(in_age in varchar2)
as
--自定义类型
type student_type is record(
id number,
name varchar2(10)
);
type students_type is ref cursor return student_type;--定义游标类型
students students_type;--声明游标变量
student student_type;--声明变量
begin
open students for select id,name from students where age<in_age;--定义游标
fetch students into student;--游标指针指向下一行
while students%found loop--遍历游标
dbms_output.put_line('编号:'||student.id||',姓名:'||student.name);
fetch students into student;--游标指针指向下一行
end loop;
close students;--关闭游标
end;
declare
p_v number;
begin
p_v:=&请输入年龄;
printstudents(p_v);
end;