--当select语句从数据库中返回的记录多余一条时,就可以使用游标(cursor)。游标可以理解为一次访问一个的一组记录。select语句将列提取到游标中,然后根据游标取得记录。使用游标时需要遵从以下的5个步骤:
(1)声明一些变量,用于保存select语句返回列值
(2)声明游标,并制定select语句
(3)打开游标
(4)从游标获取记录
(1)声明一些变量,用于保存select语句返回列值
(2)声明游标,并制定select语句
(3)打开游标
(4)从游标获取记录
(5)关闭游标
<span style="font-size:18px;">-- 游标的使用
set serveroutput on;
declare
--声明变量
sname varchar2( 20);
--声明游标
cursor student_cursor is select sn from s;
begin
--打开游标
open student_cursor;
--让游标指针往下移动
fetch student_cursor into sname ;
--判断游标指针是否指向某行记录
while student_cursor%found
--遍历
loop
dbms_output.put_line ('学生姓名' ||sname );
fetch student_cursor into sname;
end loop;
close student_cursor;
end;
--游标的使用游标,for循环是在pl/sql块中使用游标最简单的方式,它简化了对游标的处理。
--当使用游标for循环时,oracle会隐含的打开游标,提取游标数据并关闭游标。
set serveroutput on;
declare
--声明游标
cursor student_cursor is select sn, dept from s;
begin
--打开游标
--open student_cursor;
--让游标指针往下移动
for st in student_cursor
loop
--fetch student_cursor into st;
dbms_output.put_line ('学生姓名' ||st.sn ||'学生系别'||st.dept);
end loop;
close student_cursor;
end;
</span>