oracle游标

一、游标
1、简介
游标的作用相当于指针,通过游标PL/SQL程序可以一次处理查询结果集的一行。
游标存放了SQL语句的执行结果,相当于JDBC中的ResultSet
作用:用于定位结果集的行和遍历结果集
2、显式游标。通常用于查询结果集(select语句返回的查询结果)
–普通游标使用步骤
1). 声明游标 cursor 游标名 (参数) [返回值类型] is select语句;
2). 打开游标 open 游标名;
3). 从游标中取数据 fetch 游标名 into 变量;
游标名%found :找到数据;
游标名%notfound : 没有找到数据;
4). 关闭游标 close 游标名;
5). 游标的属性
%found:布尔类型。如果sql语句至少影响到一行数据,就为true,否则为false
%notfound:布尔类型。与%found相反
%rowcount:数字型参数。返回受sql语句影响的行数
%isopen:布尔型属性。当游标已经打开时返回true,否则返回false
例如:使用游标查询ruanjian171表中,学号是1710272111的学生信息,并输出结果。
declare
/声明游标/
cursor youbiao is
select * from ruanjian171 where stuno = ‘1710272111’;
student ruanjian171%rowtype; --声明变量student,数据类型和ruanjian171表中行的类型相同
begin
open youbiao; --打开游标
fetch youbiao into student; --先让指针指向结果集中的一行,并保存到student中
if youbiao%found then
dbms_output.put_line(‘学号:’ || student.stuno || ’ 姓名:’ || student.name ||
’ 性别:’ || student.sex || ’ 班级:’ || student.classname);
else
dbms_output.put_line(‘没有发现数据’);
end if;
close youbiao; --关闭游标
end;
/
例如:使用游标查询ruanjian171表中,性别是‘女’的学生信息,并输出结果。
set serveroutput on;
declare
/声明游标/
cursor youbiao is select * from ruanjian171 where sex=‘女’;
student ruanjian171%rowtype;–声明变量student,数据类型和ruanjian171表中行的类型相同
begin
open youbiao; --打开游标
fetch youbiao into student;–先让指针指向结果集中的一行,并保存到student中
while youbiao%found loop
dbms_output.put_line(‘学号:’||student.stuno||’ 姓名:’||student.name
||’ 性别:’||student.sex||’ 班级:’||student.classname);
fetch youbiao into student;–让指针指向结果集的下一行,并把结果保存到student中
end loop;
close youbiao;–关闭游标
end;
/
4、隐含游标
隐式游标的作用主要是处理数据操纵语句(增加、删除、修改)的执行结果。
隐式游标也有属性,当使用隐式游标的属性时,需要在属性前面加上默认名称——SQL
在实际的PL/SQL编程中,经常使用隐式游标来判断“更新”数据行或“修改”数据行的情况。
例如:–把杨大帅修改为杨老师
begin
update ruanjian171 set name = ‘杨老师’ where name = ‘杨大帅’;
if sql%notfound then --如果没有发现数据
dbms_output.put_line(‘没有发现杨大帅’);
else
dbms_output.put_line(‘修改成功’);
end if;
end;
/
5、游标for循环
1)for语句循环隐式游标
/使用for语句循环隐式游标,来查询ruanjian171班中女生的信息/
begin
for stu in (select * from ruanjian171 where sex = ‘女’) loop
dbms_output.put(’ 学号:’ || stu.stuno);
dbms_output.put(’ 姓名:’ || stu.name);
dbms_output.put(’ 性别:’ || stu.sex);
dbms_output.put_line(’ 班级:’ || stu.classname);
end loop;
end;
/
2)for语句循环显示游标
declare
–声明游标
cursor youbiao is select * from ruanjian171 where sex = ‘女’;
begin
for stu in youbiao loop
dbms_output.put(’ 学号:’ || stu.stuno);
dbms_output.put(’ 姓名:’ || stu.name);
dbms_output.put(’ 性别:’ || stu.sex);
dbms_output.put_line(’ 班级:’ || stu.classname);
end loop;
end;
/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值