游标分类
显式游标:使用cursor语句显式定义游标,游标被定义后,需要打开并提取游标,关闭游标。
隐式游标:由oracle为每一个dml语句创建一个隐式游标也叫做SQL游标。
BEGIN
update emp
set comm = comm *1.12
where empno = 7346;
dbms_output.put_line(SQL%ROWCOUNT || '行被更新');--使用隐式游标
if sql%notfound --使用隐式游标
then
dbms_output.put_line('不能更新员工号为7346的员工');
end if;
commit;
end;
--由于隐式游标会自动关闭,因此SQL%isopen都是false.
declare
cursor emp_cursor (p_deptno in number) return emp%rowtype --定义游标并指定参数 和返回值
is
select * from emp where deptno = p_deptno;
begin
open emp_cursor(20);
end;
游标属性
%ISOPEN:判断对应的游标变量是否打开,如果打开则返回true否则返回false.
declare
cursor emp_cursor (p_deptno in number)
is
select * from emp where deptno = p_deptno;
begin
if not emp_cursor%isopen then open emp_cursor(20);
end if;
if emp_cursor%isopen then
dbms_output.put_line('游标已经被打开');
else
dbms_output.put_line('游标还未被打开');
end if;
close emp_cursor;
end;
%FOUND:当游标被打开后,在调用fetch语句获取数据之前%found会产生NULL值。而此后每取得一行
数据,其值会为true,如果获取数据失败返回false,因此%FOUND的作用是检查是否从结果集中获取到了数据.
declare
emp_row emp%rowtype;
cursor emp_cursor (p_deptno in number)
is select * from emp where deptno=p_deptno;
begin
if not emp_cursor%ISOPEN
then open emp_cursor(20);
end if;
if emp_cursor%found is null
then
dbms_output.put_line('%found 属性为null');--在fetch获取数据之前%found为null.
end if;
loop
fetch emp_cursor into emp_row;
exit when not emp_cursor%found; --exit when emp_cursor%notfound
end loop;
close em_cursor;
end;
%notfound:此属性与%found相反。
%rowcount:用来返回到目前为止已经从游标中取出的记录的行数,当游标被打开时,%rowcount值为0,
每取得一条数据,%rowcount的值就加1.
declare
emp_row emp%rowtype;
cursor emp_cursor (p_deptno in number)
is select * from emp where deptno=p_deptno;
begin
open emp_cursor(20);
loop
fetch emp_cursor into emp_row;
exit when emp_cursor%notfound;
dbms_output.put_line('当前已提取的行数为:'||emp_cursor%rowcount||'行!');
end loop;
close emp_cursor;
end;