游标
游标分为三种:隐式游标,显式游标,REF游标
隐式游标:在pl/sql程序中执行dmlSQL时自动创建隐式游标,增删改操作;
sql%found 影响了一行或者多行时为true(既数据发生了改变)
begin
update caozyxx set mim = '';
if sql%found then
dbms_output.put_line('发生修改');
else
null;
end if;
end;
sql%notfound 没有影响任何行为时为true(既数据没有发生改变或者没有数据)
begin
update caozyxx set mim = '' where caozydm = &a;
if sql%notfound then
dbms_output.put_line('没有发生修改');
else
null;
end if;
end;
sql%rowcount 影响的行数(返回number)
begin
update caozyxx set mim = '';
dbms_output.put_line('修改了'||sql%rowcount||'行');
end;
sql%isopen 游标是否打开(始终为false)
这些隐式游标属性常用于判断
显示游标:用于处理返回多行的查询
显示游标在pl/sql块的声明部分定义查询,该查询可以返回多行
打开游标----提取行数据—把提取的行数据放到变量中----关闭游标
声明游标:cursor 游标名 is select …
–type 游标名 is ref cursor
–aa 游标名;
打开游标:open 游标名
结果集控制:fetch 游标名 into 变量
关闭游标:close 游标名
--使用pl/sql块,输入部门号,显示该部门所有的员工姓名,和他的工资。
declare
--定义游标类型
cursor sp_cursor is select caozyxm,mim from caozyxx where qiy = 1;
--定义变量
v_name caozyxx.caozyxm%type;
v_mim caozyxx.mim%type;
begin
--执行
--打开游标
open sp_cursor;
--循环取出
loop
--把游标中的内容赋给变量;
fetch sp_cursor into v_name,v_mim;
--判断aa是否为空
exit when sp_cursor%notfound;
dbms_output.put_line('姓名:'||v_name||'薪水:'||v_mim);
end loop;
close sp_cursor;
end;
带参数的显示游标
语法:cursor 游标名 (参数名,参数类型) is select …
–使用pl/sql块,输入部门号,显示该部门所有的员工姓名,和他的工资。
declare
--定义游标类型
cursor sp_cursor(qiy caozyxx.qiy%type) is select caozyxm,mim from caozyxx where qiy = qiy;
--参数一般用来做后面的查询条件
--定义变量
v_name caozyxx.caozyxm%type;
v_mim caozyxx.mim%type;
begin
--执行
--打开游标
qiy:=&a;
open sp_cursor(qiy);
--循环取出
loop
--把游标中的内容赋给变量;
fetch sp_cursor into v_name,v_mim;
--判断aa是否为空
exit when sp_cursor%notfound;
dbms_output.put_line('姓名:'||v_name||'薪水:'||v_mim);
end loop;
close sp_cursor;
end;
使用游标更新行;
declare
--定义游标类型,后面跟上for update 要更新的列
cursor sp_cursor is select caozyxm,mim from caozyxx where qiy = 1 for update of mim;
--参数一般用来做后面的查询条件
--定义变量
v_name caozyxx.caozyxm%type;
v_mim caozyxx.mim%type;
begin
--执行
--打开游标
open sp_cursor;
--循环取出
loop
--把游标中的内容赋给变量;
fetch sp_cursor into v_name,v_mim;
--判断aa是否为空
exit when sp_cursor%notfound;
--where 后面为current of 游标名
update caozyxx set mim = '1' where current of sp_cursor;
dbms_output.put_line('姓名:'||v_name||'薪水:'||v_mim);
end loop;
close sp_cursor;
commit;
end;
REF游标:处理运行时才能确认的动态SQL查询的结果
游标是一个指向上下文区的句柄或指针,可以用来控制上下文区和处理语句时上下文区发生的事情
实例:
使用pl/sql块,输入部门号,显示该部门所有的员工姓名,和他的工资。
declare
--定义游标类型
type sp_cursor is ref cursor;
--定义一个游标变量;
aa sp_cursor;
--定义变量
v_name caozyxx.caozyxm%type;
v_mim caozyxx.mim%type;
begin
--执行
--把aa和一个select结合;
--打开游标
open aa for select caozyxm,mim from caozyxx where qiy = 1;
--循环取出
loop
fetch aa into v_name,v_mim;
--判断aa是否为空
exit when aa%notfound;
dbms_output.put_line('姓名:'||v_name||'薪水:'||v_mim);
end loop;
end;