目录
🎈游标分类
1.隐式游标
2.显式游标
3.REF(引用)游标
注:在PL/SQL程序中执行DMI SQL语句时自动创建隐式游标
显式游标用于处理返回多行的查询。
✨隐式游标
在PL/SQL中使用DML语句时自动创建隐式游标
隐式游标自动声明、打开和关闭,其名为 SQL
通过检查隐式游标的属性可以获得最近执行的DML 语句的信息
隐式游标的属性有:
select * from dual
insert into dual values();
%ISOPEN - 游标是否打开,始终为FALSE
%FOUND – SQL 语句影响了一行或多行时为 TRUE
%NOTFOUND – SQL 语句没有影响任何行时为TRUE
%ROWCOUNT – SQL 语句影响的行数
在这里的话我们新建一个student表
create table student
(
sid number(3) primary key,
sname varchar2(20) not null,
sage number(2)
);
向student表中插入数据
insert into stuinfo values(1,'小王',14);
insert into stuinfo values(2,'小李',11);
insert into stuinfo values(3,'小周',12);
insert into stuinfo values(4,'小朱',13);
insert into stuinfo values(5,'小牛',12);
首先需要打开输出开关
set serverout on
begin
update student set sage = sage +10;
dbms_output.put_line('更新了'|| sql%rowcount || '行数据');
end;
/
sql是oracle自带的隐式游标 %rowcount -SQL语句影响的行数
此时查询表时会发现所有的年龄都加了10
begin
update student set sage = sage +10 where sid>50;
if sql%found then
dbms_output.put_line('更新了记录');
else
dbms_output.put_line('没有更新记录');
end if;
end;
/
%found -SQL 语句影响了一行或多行时为 TRUE
回退表中记录
rollback;
exception 异常捕捉
declare
sname1 varchar2(10);
begin
select sname into sname from student;
dbms_output.put_line(sname1);
exception
when too_many_rows then
dbms_output.put_line(取出的名字多出来一个);
end;
/
no_data_found 没有取出任何数据
too_many_rows 取出的数据过多,没有办法放到指定内存编码中
✨显式游标
当返回结果超过一行时并且需要逐条数据进行处理,就定义显示游标
显式游标在 PL/SQL 块的声明部分定义查询,该查询可以返回多行
sql Server :声明游标、打开游标、使用游标取出记录、关闭记录、deallocate丢弃游标
oracle:声明游标、打开游标、使用游标取出记录、关闭游标
declare
stu1 student%rowtype;
cursor mycursor is select * from student;
begin
open mycursor;
fetch mycursor into stu1;
while mycursor%found loop
dbms_output.put_line('学号是:'||stu1.sid||'姓名是:'||stu1.sname);
fetch mycursor into stu1;
end loop;
close mycursor;
end;
/
带参数的游标 可以调高灵活性
declare
sid1 student.sid%type;
stu1 student%rowtype;
cursor mycursor(input_no number) is select * from student where sid>input_no;
begin
sid1:=&学生学号;
open mycursor(sid1);
fetch mycursor into stu1;
while mycursor%found loop
dbms_output.put_line('学号是:'||stu1.sid||'姓名是:'||stu1.sname);
fetch mycursor into stu1;
end loop;
close mycursor;
end;
/
通过控制台输入来显示数据,我这里输入的是2,所以显示的就是大于2的
//使用显式游标更新记录
declare
stu1 student%rowtype;
cursor mycursor is select * from student where sid =2 or sid = 3 for update ;
begin
open mycursor;
fetch mycursor into stu1;
while mycursor%found loop
update student set sid = sid + 100 where current of mycursor;
fetch mycursor into stu1;
end loop;
close mycursor;
end;
/
将数据回退一下
✨循环游标
循环游标用于简化游标处理代码
当用户需要从游标中提取所有记录时使用
只能在查询的时候使用
declare
stu1 student%rowtype;
cursor mycursor is select * from student;
begin
for cur_2 in mycursor loop
dbms_output.put_line('学号是:'||cur_2.sid||'姓名是:'||cur_2.sname);
end loop;
end;
/
fetch.......bulk collect into 用于数据量大时