Oracle游标


一、游标:
游标提供了一种对从表中检索出的数据进行操作的灵活手段,就本质而言,
游标是一种能从包含多条数据记录的结果集中每次提取一条记录进行处理的机制
二、游标的分类:
1、隐式游标:名字固定为SQL
在PL/SQL中使用DML语句时自动创建隐式游标
隐式游标自动声明、打开和关闭,其名为 SQL
通过检查隐式游标的属性可以获得最近执行的DML 语句的信息
隐式游标的属性有:
SQL%FOUND – SQL 语句影响了一行或多行时为 TRUE
SQL%NOTFOUND – SQL 语句没有影响任何行时为TRUE
SQL%ROWCOUNT – SQL 语句影响的行数
SQL%ISOPEN - 游标是否打开
2、显示游标: 关键字 cursor (自己创建自己用)(声明是给值)
在声明部分 声明游标 并且赋值 ...(查询结果集)

遍历方式1
declare
-- 定义变量 stu 表 所有列的类型
t_stu stu%rowtype;
-- 创建游标 名字为 mycur 内容为 结果集
cursor mycur is select * from stu where sage > 30;
begin
--打开游标
open mycur;
--从游标中提取一行 赋值给 t_stu 变量
fetch mycur into t_stu;
--循环 如果mycur%fount 为true(内容还有) 去循环
while mycur%found loop 
-- 输出
dbms_output.put_line('姓名为:'||t_stu.sname||',年龄为:'||t_stu.sage);
-- 获取下一行数据 赋值给 t_stu变量
fetch mycur into t_stu;
end loop;
--关闭游标
close mycur;
end;

遍历方式2
declare
t_stu stu%rowtype;
cursor mycur is select * from stu where sage <= 30;
begin
open mycur;
--无限循环
loop
--取出一行
fetch mycur into t_stu;
--判断 当游标没有信息的时候 exit
exit when mycur%notfound;
dbms_output.put_line('姓名为:'||t_stu.sname||',年龄为:'||t_stu.sage);
end loop;
close mycur;
end;
遍历方式3
declare
cursor mycur is select * from stu where sage <= 30;
begin
-- 隐式创建变量 temp 类型随着 游标返回类型改变
-- 打开游标 并且获取游标第一行信息
-- 依次取出信息 赋值给变量
-- 游标遍历结束后 自动关闭游标
for temp in mycur loop
dbms_output.put_line('姓名为:'||temp.sname||',年龄为:'||temp.sage);
end loop;
end;

3、REF游标:

REF 游标和游标变量用于处理运行时动态执行的 SQL 查询(运行时给值)
创建游标变量需要两个步骤:
声明 REF 游标类型
声明 REF 游标类型的变量
用于声明 REF 游标类型的语法为:
<ref_cursor_name> 游标类型名字
TYPE <ref_cursor_name> IS REF CURSOR
[RETURN <return_type>];

declare
-- 声明游标类型 
-- 有 return 属于强类型 必须 查询对应表
type my_ref_type is ref cursor return stu%rowtype;
--声明游标变量
my_ref_cor my_ref_type; --变量 类型
t_stu stu%rowtype;
begin
open my_ref_cor for select * from stu;
fetch my_ref_cor into t_stu;
while my_ref_cor%found loop
dbms_output.put_line('姓名为:'||t_stu.sname||',年龄为:'||t_stu.sage);
fetch my_ref_cor into t_stu;
end loop;
close my_ref_cor;
end;
美好生活
原文地址:https://www.cnblogs.com/ssbydk/p/curtor.html