码迷,mamicode.com
首页 > 数据库 > 详细

oracle游标

时间:2018-11-05 10:10:40      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:cursor   控制语句   影响   name   declare   arc   current   update   返回   

一.什么是游标

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;

oracle游标

标签:cursor   控制语句   影响   name   declare   arc   current   update   返回   

原文地址:https://www.cnblogs.com/MrTanJunCai/p/9907441.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!