(一)、游标的用法学习
(a)、游标就是指在某个结果集上的指针,通过这个指针的移动,我们得以遍历整个结果集
(b)、游标的使用步骤
(1)声明游标
(2)打开游标
(3)处理游标中的数据
(4)关闭游标
(c)、最常用的游标属性有以下四个:
%isopen,boolean类型变量,用来代表游标是否打开。
%notfound,boolean类型变量,如果最近的fetch语句没有返回一条记录,取true。
%found,boolean类型变量,如果最近的fetch语句取到了记录,取true。
%rowcount,number类型变量,用来代表目前fetch到的记录的总行数。
(二)、游标的遍历方式
(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;
(三)、使用游标更新结果集
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;
PL/SQL脚本语言游标的使用学习笔记
猜你喜欢
转载自wlxt-8436.iteye.com/blog/1776292
今日推荐
周排行