Oracle 游标使用总结

oracle游标分为显示游标和隐式游标。

显示游标(explicit cursor):在pl/sql程序中定义的、用于查询的游标称作显示游标。

隐式游标(implicit cursor):是指非pl/sql程序中定义的、而且是在pl/sql中使用update/delete语句时,oracle系统自动分配的游标。


一.显示游标
1.使用步骤

(1)定义 (2)打开 (3)使用 (4)关闭

2.使用演示

首先创建测试用表student,脚本如下:


复制代码 代码如下:

create table “student” (

“stuname” varchar2(10 byte),

“stuno” varchar2(4 byte),

“age” number,

“gender” varchar2(2 char)

)

(1).使用while循环处理游标

create or replace procedure proc_stu1 as

begin

–显示游标使用,使用while循环

declare

–1.定义游标,名称为cur_stu

cursor cur_stu is

select stuno,stuname from student order by stuno;

–定义变量,存放游标取出的数据

v_stuno varchar(4);

v_stuname varchar(20);

begin

–2.打开游标cur_stu

open cur_stu;

–3.将游标的当前行取出存放到变量中

fetch cur_stu into v_stuno,v_stuname;

while cur_stu%found –游标所指还有数据行,则继续循环

loop

–打印结果

dbms_output.put_line(v_stuno||’->’||v_stuname);

–继续将游标所指的当前行取出放到变量中

fetch cur_stu into v_stuno,v_stuname;

end loop;

close cur_stu; –4.关闭游标

end;

end proc_stu1;

(2).使用if..else代替while循环处理游标

create or replace procedure proc_stu2 as

begin

–显示游标使用,使用if判断

declare

–1.定义游标,名称为cur_stu

cursor cur_stu is

select stuno,stuname from student order by stuno;

–定义变量,存放游标取出的数据

v_stuno varchar(4);

v_stuname varchar(20);

begin

–2.打开游标cur_stu

open cur_stu;

–3.将游标的当前行取出存放到变量中

fetch cur_stu into v_stuno,v_stuname;

loop

if cur_stu%found then –如果游标cur_stu所指还有数据行

–打印结果

dbms_output.put_line(v_stuno||’->’||v_stuname);

–继续将游标所指的当前行取出放到变量中

fetch cur_stu into v_stuno,v_stuname;

else

exit;

end if;

end loop;

close cur_stu; –4.关闭游标

end;

end proc_stu2;

(3).使用for循环处理游标

create or replace procedure proc_stu3 as

begin

–显示游标使用,使用for循环

declare

–定义游标,名称为cur_stu

cursor cur_stu is

select stuno,stuname from student order by stuno;

begin

for stu in cur_stu

loop

dbms_output.put_line(stu.stuno||’->’||stu.stuname);

–循环做隐含检查 %notfound

end loop;

–自动关闭游标

end;

end proc_stu3;

(4).常用的使用exit when处理游标

create or replace

procedure proc_stu1_1 as

begin

–显示游标使用,使用exit when循环

declare

–1.定义游标,名称为cur_stu

cursor cur_stu is

select stuno,stuname from student order by stuno;

–定义变量,存放游标取出的数据

v_stuno varchar(4);

v_stuname varchar(20);

begin

–2.打开游标cur_stu

open cur_stu;

loop

–3.将游标的当前行取出存放到变量中

fetch cur_stu into v_stuno,v_stuname;

exit when cur_stu%notfound; –游标所指还有数据行,则继续循环

–打印结果

dbms_output.put_line(v_stuno||’->’||v_stuname);

end loop;

close cur_stu; –4.关闭游标

end;

end proc_stu1_1;

二.隐式游标

1.使用演示

create or replace procedure proc_stu4 as

begin

–隐式游标使用

update student set stuname=’张燕广’ where stuno=’1104′;

–如果更新没有匹配则插入一条新记录

if sql%notfound then

insert into student(stuno,stuname,age,gender)

values(‘1104′,’张燕广’,18,’男’);

end if;

end proc_stu4;

2.说明

所有的sql语句在上下文区内部都是可执行的,因为都有一个游标指向上下文区,此游标就是

sql游标,与现实游标不同的是,sql游标在pl/sql中不需要打开和关闭,而是在执行update、

delete是自动打开和关闭。

上面例子中就是通过sql%notfound游标属性判断update语句的执行结果决定是否需要插入新记录。

(0)
上一篇 2022年3月22日
下一篇 2022年3月22日

相关推荐