oracle--游标(cursor)

1.游标是:

一种PL/SQL控制结构,相当于java中的Iterator ,它是指向结果集的指针。指向结果集第一条记录的前一条,每次fetch 都会向下移动下

游标并不是一个数据库对象,只是存留在内存中

2. 作用:方便对表的行数据逐条进行处理

---------------

--注意:fetch是下移动,%found是判断此行有无数据的--这是作为循环的跳出条件的,定要注意--for循环除外

---注意:%found 与%notfound的区别--%found是判断此行有没有数据,有的的时候执行;%notfound 判断当前行是否有数据,没有则停止执行

--在打开游标之前最好先判断游标是否已打开 %isopen

eg:

IF mycur%ISOPEN THEN
null ;
ELSE
OPEN mycur ;
END IF ;

--可以使用ROWCOUNT对游标所操作的行数进行记录。%rowcount

----------------

3.使用游标;

声明游标

cursor c is --声明
select * from emp; ---结果集

打开游标

open c;---此时才会指向 结果集;--指向结果集第一条记录之前。

循环抓取游标

fetch c into 记录类型的变量;---将抓取得游标赋给一个记录类型的变量

---每次只能读取一行,若是想要遍历,就要有循环。
---每当遇到fetch 指针就会向下移动一下。

关闭游标

close c;
---

eg:

declare
cursor c is
select * from emp;
v_record_emp emp%rowtype;
v_sal emp.sal%type;

begin
open c;
loop
fetch c into v_record_emp;
exit when(c%notfound);
v_sal := v_record_emp.sal;
if(v_sal < 1200) then
v_record_emp.sal := v_sal + 500;
elsif(v_sal < 1500) then
v_record_emp.sal := v_sal + 300;
else
v_record_emp.sal := v_sal + 300;
end if;
update emp set sal=v_record_emp.sal where empno=v_record_emp.empno;
end loop;
close c;
commit;
end;

------------
使用for循环可以简化游标使用时候的代码(比较常用)

declare
cursor c is
select * from emp;
v_sal emp.sal%type;

begin
for v_record_emp in c loop---就完成了打开游标,抓取游标,和关闭游标
v_sal := v_record_emp.sal;
if(v_sal < 1200) then
v_record_emp.sal := v_sal + 500;
elsif(v_sal < 1500) then
v_record_emp.sal := v_sal + 300;
else
v_record_emp.sal := v_sal + 300;
end if;
update emp set sal=v_record_emp.sal where empno=v_record_emp.empno;
end loop;
commit;
end;

-------------------
游标分:

1.可更新的游标

declare
cursor c is
select * from emp for update;--比普通的多 for update

begin
for v_record_emp in c loop
if(v_record_emp.sal<2000) then
update emp set sal=sal*2 where current of c; --条件 current of c
elsif(v_record_emp.sal=5000) then
delete from emp where current of c;
end if;
end loop;
commit;
end;

----需要用 for update 来标识 遍历是给该结果集更新为目的的

----可更新的游标,我们能够用current of c获取到 当前记录


2.带参数的游标

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;

---带参数的目的是为了 设置获取参数的条件

---游标的参数是在open游标的时候赋值的---open c(30,'clerk');


3.隐士游标

当用户在PL/SQL 中使用数据操纵语句(DML)时,

oracle预先定义一个名称为SQL的隐式游标,

通过 检查隐式游标的属性获取与最近执行的SQL语句相关信息。

在执行DML语句之后,隐式游标属性返回信息。

隐式游标属性包括: %found %notfound %rowcount %isopen

eg: sql%rowcount中的sql是oracle的内部游标,rowcount的意思是之前的dml sql语句影响的多少行数据。
eg:
declare
begin
update B_BARCODE_JINZHI_T set jinzhi='00';
dbms_output.put_line(to_char(sql%rowcount));
end;

---结果: 5
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值