oracle游标

一.什么是游标

CCL: Cursor Control Langage 游标控制语句


游标: 指向数据库结果集的一个指针,类似于 Iterator


使用游标 查询结果集,游标指向的是结果集中第一条记录之前的位置

如果进行fetch操作, 每fetch一次,指针向后移动一位,并且返回当前

指针指向的记录


二.什么时候用游标

如果查出来的记录 只有一条 可以直接 select * into v_temp

如果返回的记录 是多条数据 ,需要使用游标来遍历这些数据


三.如何使用

1.声明游标

2.开启游标

3.循环抓取游标

4.关闭游标


********************************do..while遍历游标**********************************

需求: 使用游标打印所有员工的姓名


--使用游标来打印所有员工的姓名
--使用do..while
declare
--1.声明游标
cursor c is
select * from emp;
v_emp emp%rowtype;
begin
--2.开启游标
open c;
--3.循环抓取游标
loop
fetch c into v_emp;

exit when(c%notfound);

dbms_output.put_line(v_emp.ename);

end loop;

--4.关闭游标
close c;

end;


select * from emp


********************************while遍历游标**********************************


declare
cursor c is
select * from emp;
v_emp emp%rowtype;
begin
open c;
fetch c into v_emp;
while(c%found) loop
dbms_output.put_line(v_emp.ename);
fetch c into v_emp;
end loop;
close c;
end;


********************************for遍历游标*************************************


--使用for循环遍历游标

--不需要开启、循环抓取、关闭游标,for循环会自动帮你完成以上工作

declare
--1.声明游标
cursor c is
select * from emp;

--v_emp emp%rowtype;
begin
for v_emp in c loop
dbms_output.put_line(v_emp.ename);
end loop;

 

end;


********************************带参数的游标*************************************
--需求: 查询 部门编号为10的 并且 工种为CLERK的员工的姓名和工资

declare
cursor c(v_deptno emp.deptno%type,v_job emp.job%type) is
select ename,sal from emp where deptno=v_deptno and job=v_job;
begin
for v_temp in c(30,'CLERK') loop
dbms_output.put_line(v_temp.ename);
end loop;
end;


********************************可更新的游标*************************************
--可更新的游标

declare
cursor c is
select * from emp1 for update;
begin
for v_temp in c loop
if(v_temp.sal<1200) then
update emp1 set sal=sal+500 where current of c;--当前游标指向的记录
elsif(v_temp.sal<1500) then
update emp1 set sal=sal+300 where current of c;--当前游标指向的记录
else
update emp1 set sal=sal+100 where current of c;--当前游标指向的记录
end if;
end loop;

end;


每次使用empno 判断到底给哪个记录更新比较麻烦, 可以使用可更新的游标 直接给当前指针指向的记录更新


current of c--表示当前指针指向的记录

 

********************************隐式游标*************************************


SQL%rowcount 返回最后一条sql语句受影响的行数

一般用来判断上一条 sql语句 是否成功 或影响了几条记录

 

--隐式游标 SQL%rowcount

declare
v_count number(2);
v_desc varchar2(12);
begin
update dept set dname='aaa' where deptno=40;
v_count := SQL%rowcount;

if(v_count >= 1) then
v_desc := '部门修改成功';
else
v_desc := '部门修改失败';
end if;

dbms_output.put_line(v_desc);
end;

转载于:https://www.cnblogs.com/MrTanJunCai/p/9907441.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值