光标的概念
result set ---->结果集
在pl/sql中使用光标代表一个’集合’;
定义:
cursor 光标名 [(参数名 数据类型)]
eg:
cursor c1 is select name from test;
定义了一个光标c1,该内容是所有名称name的集合
光标取值
%found 是光标取到值为真
%notfound 是光标没有取到值时为真
/*
光标属性
%fount %notfount
*/
declare
cursor cemp is
select name from test;
pname test.name%type;
begin
--打开光标
open cemp;
loop
fetch cemp
into pname;
--思考 1 循环什么时候退出? 2 fetch不一定能取到记录
--exit when 没有取到记录;
exit when cemp%notfound;
dbms_output.put_line('名字是' || pname);
end loop;
--关闭光标
close cemp;
end;
光标举例
declare
cursor cemp is
select name, age from test;
pname test.name%type;
page test.age%type;
begin
open cemp;
loop
fetch cemp
into pname, page;
exit when cemp%notfound;
if pname = '王思' then
update test set test.age = page + 1 where name = pname;
else
update test set test.age = page + 10 where name = pname;
end if;
end loop;
close cemp;
commit;
dbms_output.put_line('年龄增加完成');
end;
光标属性与限制
/*
%found %notfound
%isopen 判断光标是否打开
%rowcount 影响的行数
*/
declare
cursor cemp is select name,age from test;
pname test.name%type;
page test.age%type;
begin
open cemp;
if cemp%isopen then
dbms_output.put_line('光标打开');
end if;
close cemp;
end;
修改光标限制
alter system set open_cursors=400 scope=both;
scope取值有三个:both/memory/spfile
memory:只更改当前实例,不更改参数文件
spfile:数据库需要重启,只更改参数文件,不更改当前实例
both:二者都更改
带参数的光标
cursor 光标名[参数名 数据类型] is select * from…
eg:查询某个年纪的人
declare
cursor cemp(aa number) is select name,type from test where test.age=aa;
pname test.name%type;
ptype test.type%type;
begin
open cemp(33);
loop
fetch cemp into pname,ptype;
exit when cemp%notfound;
if pname=13 then
dbms_output.put_line(ptype);
end if;
end loop;
close cemp;
end;