@feifeifan //oracle游标详解
游标基础:游标有一种最简单的形式,我们可以把它想象成一个指针,指向一个查询结果,这个查询可以指向一个或多个数据库表。
比如声明一个游标:
cursor staff_cursor is select * from test01;--不含参数
cursor staff_cursor(staff_id_new in varchar2) is select * from test01 where staff_id =staff_id_new;--喊参数游标
cursor staff _cur return test01%rowtypes is select * from test01;--含return子句的游标
打开游标:
open staff_cursor;
从游标中提出数据:
fetch staff_cursor into staff_rec;
关闭游标:
close staff_cursor;
eg(显示游标):
declare
cursor staff_cursor is select * from test01;
staff_rec staff_cursor%rowtype;
begin
open staff_cursor;
fetch staff_cursor into staff_rec;
if staff_cursor%found
then
update test01 set staff_name='刘想' where staff_id=staff_rec.staff_id;
end if;
close staff_cursor;
exception
when others then
if staff_cursor%isopen then
closse staff_cursor;
end if;
end;
eg(隐式游标):
declare
cursor staff_cursor is select * from test01;
staff_rec staff_cursor%rowtype;
begin
for staff_rec in staff_cursor
loop
update test01 set staff_name='刘想' where staff_id=staff_rec.staff_id;
exit when staff_cursor%notfound;
end loop;
end ;
游标属性介绍
名称 | 描述 |
---|---|
%FOUND | 如果记录被成功获取,返回true ,否则返回false |
%NOTFOUND | 如果记录不被成功获取,返回true ,否则返回false |
%ROWCOUNT | 返回目前为止,从游标中提取记录数 |
%ISOPEN | 如果游标是打开的,返回true,否则返回false |
%BULK_ROWCOUNT | 返回被forall语句修改的记录数量 |
%BULK_EXCEPTIONS | 返回被forall语句修改的记录出现的异常信息 |
转载: oracle forall/bulk collect 语句用法详解
显示游标较隐式游标的来说可追溯,它可以控制数据库提取信息所设计的不同plsql步骤,可以决定什么时候open,什么时候fetch,什么时候close,但是相对于优化后的隐式游标来说,效率比显示更高。
function func_jealousy (name_in in friends.name%type)
return number
as
cursor jealousy_cur is select locaiton from friends where name = upper(name_in);
jealousy_rec jealousy_cur %rowtype;
ret number;
begin
open jealousy_cur ;
fetch jealousy_cur into jealousy_rec;
if jealousy_cur %found
then
if
jealousy_rec.location ='ssds' then ret :=10;
elsif jealousy_rec.location='sss' then ret:=1;
end if;
end if;
close jealousy_cur ;
return ret;
exception
when others then
if jealousy_cur %isopen then
close jealousy_cur ;
end if ;
end ;