PL/SQL脚本语言游标的使用学习笔记

[color=darkred](一)、游标的用法学习[/color]
(a)、游标就是指在某个结果集上的指针,通过这个指针的移动,我们得以遍历整个结果集
(b)、游标的使用步骤
(1)声明游标
(2)打开游标
(3)处理游标中的数据
(4)关闭游标

(c)、最常用的游标属性有以下四个:
%isopen,boolean类型变量,用来代表游标是否打开。
%notfound,boolean类型变量,如果最近的fetch语句没有返回一条记录,取true。
%found,boolean类型变量,如果最近的fetch语句取到了记录,取true。
%rowcount,number类型变量,用来代表目前fetch到的记录的总行数。

[color=darkred](二)、游标的遍历方式[/color]
(1)、Loop循环遍历游标 利用loop循环和%notfound属性实现游标的遍历
(2)、While循环遍历游标 利用while循环配合%found属性实现游标的遍历
(3)、for循环遍历游标 利用for循环遍历游标,不需要打开游标,也不需要关闭,甚至不用声明循环变量,最简单

--用三种循环遍历游标
declare
--声明游标
cursor c_emp(v_deptno number) is select * from emp e where e.deptno=v_deptno;
--声明一个游标的行变量 loop遍历或者while loop遍历时使用
c_emp_row c_emp%rowtype;
begin
/* --loop 遍历
--打开游标
open c_emp(10);
--使用游标
loop
fetch c_emp into c_emp_row ;--取数据
exit when c_emp%notfound;
dbms_output.put_line(c_emp_row.ename);
end loop;
--关闭游标
close c_emp;*/
dbms_output.put_line('----------------------for循环遍历游标------------------------');
--for循环遍历游标
for emp_row in c_emp(10) loop
dbms_output.put_line(emp_row.ename);
end loop;
dbms_output.put_line('---------------------while循环遍历游标-------------------------');
--while循环遍历游标
open c_emp(10);
fetch c_emp into c_emp_row ;--取数据
while c_emp%found loop
dbms_output.put_line(c_emp_row.ename);
fetch c_emp into c_emp_row ;--取数据
end loop;
close c_emp;
end;

[color=darkred](三)、使用游标更新结果集[/color]
select语句后面添加for update来提示oracle锁定记录以便进行更新,
用where current of 来指明操作是添加在当前游标所指向的记录上。
示例
declare
--
cursor c is select * from emp2 e for update;
v_temp c%rowtype;
begin
for v_temp in c loop
dbms_output.put_line(v_temp.sal);
if(v_temp.sal < 2000) then
update emp2 set sal =7000 where current of c;
elsif(v_temp.sal = 5000) then
delete from emp2 where current of c;
end if;
end loop;
end;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值