游标(光标): 是用来操作查询结果集,相当于是JDBC中ResultSet
语法: cursor 游标名[(参数名 参数类型)] is 查询结果集
开发步骤:
1. 声明游标
2. 打开游标 open 游标名
3. 从游标中取数据 fetch 游标名 into 变量
游标名%found :找到数据
游标名%notfound : 没有找到数据
4. 关闭游标 close 游标名
系统引用游标
1. 声明游标 : 游标名 sys_refcursor
2. 打开游标: open 游标名 for 结果集
3. 从游标中取数据
4. 关闭游标
for循环遍历游标:
不需要声明额外变量
不需要打开游标
不需要关闭游标
Oracle:> declare
--游标
cursor vrows is select * from 表1;
--s声明变量,记录一行数据
vrow 表1%rowtype;
begin
--1.打开游标
open vrows;
--2.从游标提取数据
--循环取数据
loop
fetch vrows into vrow;
exit when vrows%notfound;
dbms_output.put_line('姓名:'||vrow.ename ||' 工资: ' || vrow.sal);
end loop;
--3.关闭游标
close vrows;
end;
--输出指定部门下的员工姓名和工资
Oracle:>
declare
--声明游标
cursor vrows(dno number) is select * from 表1 where deptno = dno;
--声明变量
vrow 表1%rowtype;
begin
--1.打开游标 , 指定10号部门
open vrows(10);
--2. 循环遍历,取数据
loop
fetch vrows into vrow;
exit when vrows%notfound;
dbms_output.put_line('姓名:'||vrow.ename ||' 工资: ' || vrow.sal);
end loop;
close vrows;
end;
--系统引用游标
--输出员工表中所有的员工姓名和工资
Oracle:> declare
--声明系统引用游标
vrows sys_refcursor;
--声明一个变量
vrow 表1%rowtype;
begin
--1.打开游标
open vrows for select * from 表1;
--2.取数据
loop
fetch vrows into vrow;
exit whe