-- 游标的分类 :显示游标(select 返回多行数据) 和隐式游标(select into ) 默认游标名称sql
使用显示游标:
1.定义游标
cursor 游标名 is select语句。。。
2.打开游标
open 游标名
3.提取数据
fetch 游标名 (bull collection) into table/record
4.关闭游标
close 游标名
判断游标有没有提取到数据 %notfound :根据fetch 的返回的最新结果
-- 查询所有的部门 使用行记录提取游标的数据
declare
v_dept dept%rowtype;
cursor dept_cursor is select * from dept;
begin
open dept_cursor; -- 打开游标
loop
fetch dept_cursor into v_dept; --先提取数据,再判断退出条件
exit when dept_cursor%notfound;
dbms_output.put_line('部门编号:'||v_dept.deptno||'部门名称:'||v_dept.dname);
end loop;
close dept_cursor; --关闭游标
end;
--用table结构提取游标数据 提取游标数据到table,索引值引用%rowcount 提取到的实际行数,table 的索引值从1开始
declare
type v_dept is table of dept%rowtype index by binary_integer; --定义表类型
cursor dept_cursor is select * from dept;
v_dept_tb v_dept; --定义表类型的变量
begin
open dept_cursor; -- 打开游标
fetch dept_cursor bulk collect into v_dept_tb; --一次性提取游标数据到v_dept_tb
dbms_output.put_line('游标提取到的行数:'||dept_cursor%ROWCOUNT);
close dept_cursor; --关闭游标
for i in v_dept_tb.first..v_dept_tb.last loop
dbms_output.put_line('table索引值:'||i);
dbms_output.put_line('部门编号:'||v_dept_tb(i).deptno||'部门名称:'||v_dept_tb(i).dname);
end loop;
end;
--游标for循环简化游标处理 当使用游标for循环时,oracle会隐含地打开游标,提取数据并关闭游标。
declare
cursor dept_cursor is select * from dept;
begin
for dept_record in dept_cursor loop
dbms_output.put_line('部门编号:'||dept_record.deptno||'部门名称:'||dept_record.dname);
end loop;
end;
-- 游标for循环简化游标处理 当使用游标for循环时,可以直接使用子查询。
declare
begin
for dept_record in(select * from dept) loop
dbms_output.put_line('部门编号:'||dept_record.deptno||'部门名称:'||dept_record.dname);
end loop;
end;
转载请注明原文地址: https://ju.6miu.com/read-16153.html