一、概念
游标(cursor)是数据库系统在内存中开设的一个数据缓冲区,存放SQL语句的执行结果,相当于JDBC中的ResultSet
二、作用
用于定位结果集的行和遍历结果集
三、定义
--定义游标
cursor 游标名 ( 参数 ) [返回值类型] is select语句;
四、使用
1.普通游标使用步骤
--普通游标使用步骤
1. 声明游标 cursor 游标名 ( 参数 ) [返回值类型] is select语句;
2. 打开游标 open 游标名;
3. 从游标中取数据 fetch 游标名 into 变量;
游标名%found :找到数据;
游标名%notfound : 没有找到数据;
4. 关闭游标 close 游标名;
--输出员工表中所有的员工姓名和工资(不带参数游标)
/*
游标:所有员工
声明一个变量,用来记录一行数据 %rowtype
*/
declare
--1.声明游标
cursor vrows is select * from emp;
--声明变量,记录一行数据
vrow emp%rowtype;
begin
--2.打开游标
open vrows;
--3.循环遍历,取数据
loop
fetch vrows into vrow;
exit when vrows%notfound;
dbms_output.put_line('姓名:'||vrow.ename ||' 工资: ' || vrow.sal);
end loop;
--4.关闭游标
close vrows;
end;
--输出指定部门下的员工姓名和工资
/*
游标: 指定部门的所有员工
声明一个变量记录一行数据
*/
declare
--1.声明游标
cursor vrows(dno number) is select * from emp where deptno = dno;
--声明变量
vrow emp%rowtype;
begin
--2.打开游标 , 指定10号部门
open vrows(10);
--3.循环遍历,取数据
loop
fetch vrows into vrow;
exit when vrows%notfound;
dbms_output.put_line('姓名:'||vrow.ename ||' 工资: ' || vrow.sal);
end loop;
--4.关闭游标
close vrows;
end;
2.系统引用游标使用步骤
--系统级别游标使用
1. 声明游标 : 游标名 sys_refcursor;
2. 打开游标: open 游标名 for select结果集;
3. 从游标中取数据
4. 关闭游标
--系统引用游标
--输出员工表中所有的员工姓名和工资
declare
--1.声明系统引用游标
vrows sys_refcursor;
--声明一个变量
vrow emp%rowtype;
begin
--2.打开游标
open vrows for select * from emp;
--3.循环遍历,取数据
loop
fetch vrows into vrow;
exit when vrows%notfound;
dbms_output.put_line('姓名:'||vrow.ename ||' 工资: ' || vrow.sal);
end loop;
--4.关闭游标
close vrows;
end;
3.使用for循环遍历游标(不需要声明额外变量/不需要打开游标/不需要关闭游标 )
--使用for循环遍历游标
declare
--声明一个游标
cursor vrows is select * from emp;
begin
for vrow in vrows loop
dbms_output.put_line('姓名:'||vrow.ename ||' 工资: ' || vrow.sal || '工作:'|| vrow.job);
end loop;
end;