理解游标
游标是什么?
游标是用来存储多条查询数据的一种数据结构,他有一个指针,可以从上而下移动,可以使用循环语句对每条数据进行遍历。
为什么使用游标?
比如我们简单执行一条查询语句,正常情况下我们会直接查询到所有结果,但有时候我们想对这些查询数据进行选择和处理,这时就需要使用游标,对查询到的结果集进行逐条遍历。
使用游标
创建表并插入测试数据
--创建student表
create table student(
id number(5),
student_no number(10),
name varchar2(30)
);
insert into student(id,student_no,name)values(1,180601,'小明');
insert into student(id,student_no,name)values(2,180602,'小李');
显式游标
declare
-- 1、声明游标,将查询结果存储到游标中
cursor cur_stu is select * from student;
-- 创建一个游标类型的变量
v_stu cur_stu%rowtype;
begin
-- 2、开启游标
open cur_stu;
-- 3、获取数据(一次获取一行),可进行循环遍历获取
fetch cur_stu into v_stu;--游标下移
dbms_output.put_line('id:' || v_stu.id || ' 学号:' || v_stu.student_no || ' 姓名:' || v_stu.name);
-- 4、关闭游标
close cur_stu;
end;
执行结果
id:1 学号:180601 姓名:小明
隐式游标
隐式游标自动创建、自动声明、打开、关闭,默认游标名sql,通常与游标函数一起使用
游标函数
%found:从结果集中查询记录是否有值
%notfound: 查询是否没有值(用于退出循环)
%rowcount:当前执行的sql语句记录总数
%isopen: 游标是否已经打开
隐式用法
declare
v_name student.name%type;
begin
select name into v_name from student where id = 2;
if SQL%FOUND then
dbms_output.put_line('学生名字:' || v_name);
else
dbms_output.put_line('无记录');
end if;
end;
执行结果
学生名字:小李
显式用法
declare
cursor cur_stu is select t.name from student;
v_stu cur.stu%type;
begin
open cur_stu; --打开游标
fetch cur_stu into v_name; --游标下移
loop
if cur_stu%found then
dbms_output.put_line('姓名:' || v_stu.name);
fetch cur_stu into v_stu;
elsif cur_stu%notfound then
exit; --退出循环
end if;
end loop;
if cur_stu%isopen then
close stu_name; --关闭游标
end if;
end;