零基础学Oracle资源地址: 零基础学oracle(百度云盘资源)
游标提供了一种从表中检索数据并进行操作的灵活手段,游标主要用在服务器上,处理由客户端发送给服务器端的SQL语句,或是批处理、存储过程、触发器中的数据处理请求。游标的作用相当于指针,通过游标PL/SQL程序可以一次处理查询结果集中的一行,并可以对该行数据执行特定操作,从而为用户在处理数据的过程中提供了很大方便。
在Oracle中,通过游标操作数据主要使用显式游标和隐式游标,另外,还有具有引用类型的ref游标。
游标属性:
声明游标 → 打开游标 → 提取数据 → 关闭游标
declare
book_rec book%rowtype;
cursor book_cur is
select id,title from book;
begin
open book_cur;
fetch book_cur into book_rec;
close book_cur;
end;
declare
book_rec book%rowtype;
cursor book_cur is select id,title from book;
begin
open book_cur;
fetch book_cur into book_rec;--提取一行记录到变量book_rec
while book_cur%found loop
dbms_output.put_line(book_rec.id || ' -- ' || book_rec.title);
fetch book_cur into book_rec;
end loop;
close book_cur;
end;
declare
book_rec book%rowtype;
cursor book_cur is
select id,title from book for update;
begin
open book_cur;
fetch book_cur into book_rec;
while book_cur%found loop
dbms_output.put_line(book_rec.id || ' -- ' || book_rec.title);
fetch book_cur into book_rec;
end loop;
close book_cur;
end;
如果你想删除或者更新被Select For Update引用的记录,你可以使用Where Current Of语句
declare
book_rec book%rowtype;
cursor book_cur is
select id, title from book for update;
begin
open book_cur;
loop
fetch book_cur
into book_rec;
if book_cur%notfound then
exit;
else
update book set title=title || '*' where current of book_cur;
dbms_output.put_line(book_rec.id || ' -- ' || book_rec.title);
end if;
end loop;
--commit;
close book_cur;
end;
declare
cursor book_cur is
select id, title from book for update;
beginfor
book_rec in book_cur loop
dbms_output.put_line(book_rec.id || ' -- ' || book_rec.title);
end loop;
end;
declare
type book_cur_type is ref cursor;
book_cur book_cur_type;
book_rec book%rowtype;
begin
open book_cur for
select * from book ;
loop
fetch book_cur into book_rec;
exit when book_cur%notfound;
dbms_output.put_line(book_rec.id || ' -- ' || book_rec.title);
end loop;
end;
declare
type ref_cur_type is ref cursor;
emp_cur ref_cur_type;
cursor dept_cur(p_deptno number) is
select a.dname, cursor(select * from emp where deptno = a.dno)
from dept a where a.dno = p_deptno;
v_dname dept.dname%type;
emp_rec emp%rowtype;
begin
open dept_cur(&no);
loop
fetch dept_cur into v_dname,emp_cur;
exit when dept_cur%notfound;
dbms_output.put_line('部门名称:' || v_dname);
loop
fetch emp_cur into emp_rec;
exit when emp_cur%notfound;
dbms_output.put_line(' 姓名:' || emp_rec.ename || ' ,工资:'||emp_rec.sal);
end loop;
end loop;
close dept_cur;
end;