游标的定义:
游标的作用
在前面的文章中有提到过,查询结果如果超过一行,就需要使用游标。在文章”
Oracle数据中的PL/SQL介绍“。
创建步骤:
定义一个游标
语法:CURSOR cursor_name is select _statement;
打开游标
语法:open cursor_name;
提取数据
使用fetch,fetch关键字会抓取当前行的记录,并将记录指针下移一行。就像JdbC中的ResultSet一样。
语法:fetch cursor_name into variable1,variable2.
游标的一些属性
关闭游标
语法:close cursor_name
示例代码如下:
普通的方法:
[sql]
---游标的使用
declare
--定义一个游标,将tab_stu所有数据提取出来
cursor c_tab_stu is
select * from tab_stu;
r_tab_stu tab_stu%rowtype;--使用rowtype存储游标数据
begin
--打开游标
open c_tab_stu;
--提取数据
fetch c_tab_stu into r_tab_stu;
dbms_output.put_line('stu_id:'||r_tab_stu.stu_id);
dbms_output.put_line('stu_name:'||r_tab_stu.stu_name);
dbms_output.put_line('stu_age:'||r_tab_stu.stu_age);
--关闭游标
close c_tab_stu;
end;
使用循环的方法
[sql]
--使用循环提取所有记录
declare
--定义一个游标,将tab_stu所有数据提取出来
cursor c_tab_stu is
select * from tab_stu;
r_tab_stu tab_stu%rowtype;--使用rowtype存储游标数据
begin
--打开游标
open c_tab_stu;
--提取数据
loop
fetch c_tab_stu into r_tab_stu;
--退出条件,也就是上面图片的属性的值
exit when c_tab_stu%notfound;
dbms_output.put_line('stu_id:'||r_tab_stu.stu_id);
dbms_output.put_line('stu_name:'||r_tab_stu.stu_name);
dbms_output.put_line('stu_age:'||r_tab_stu.stu_age);
end loop;
--关闭游标
close c_tab_stu;
end;
使用含有参数的游标和嵌套循环:
[sql]
--含有条件的游标
--实现目标是,查询每个班的学生
declare
--先要定义两个游标
--定义tab_class游标
cursor s_tab_class is
select * from tab_class;
--定义tab_stu游标,但是这里需要一个参数,就是班级的id
cursor s_tab_stu(v_class_id number) is
select * from tab_stu where class_id=v_class_id;
--定义两个存储变量
--定义tab_class
v_tab_class_rowtype tab_class%rowtype;
--定义tab_stu
v_tab_stu_rowtype tab_stu%rowtype;
begin
--打开游标
open s_tab_class;
loop
--提取数据
fetch s_tab_class into v_tab_class_rowtype;
exit when s_tab_class%notfound;
dbms_output.put_line('班级:'||v_tab_class_rowtype.class_name||'含有');
--嵌套循环,遍历当前班级的学生
open s_tab_stu(v_tab_class_rowtype.class_id);
loop
fetch s_tab_stu into v_tab_stu_rowtype;
exit when s_tab_stu%notfound;
dbms_output.put_line(v_tab_stu_rowtype.stu_name);
end loop;
close s_tab_stu;
end loop;
close s_tab_class;
end;