oracle 游标--cursor

游标:临时存储从数据库中提取的数据块
为了执行速度,把数据从放在磁盘中的表中调到计算机内存中进行处理

declare    --显式游标
   emprow emp%rowtype;--定义保存游标检索结果行的记录变量

   cursor emp_cur--定义游标 关联SQL语句
   is
   select * from emp where deptno is not null;
   begin
     open emp_cur; --打开游标    sql语句被执行 ,查询的数据保存到内存中,游标指向该内存区域
     loop--循环检索游标
       fetch emp_cur into emprow;--提取游标内容  提取游标中的数据到游标行中
       dbms_output.put_line('bingo');
       exit when emp_cur%notfound;--游标检索完退出循环
       end loop;
       close emp_cur; --关闭游标
       end;
   *--隐式游标   隐式游标自动关闭 所以%isopen属性总是false
   oracle执行DML(insert、 update、 delete、 select into)语句时,会自动隐式地创建游标,自动打开、自动关闭、自动提交
   通过关键字SQL来访问游标属性SQL%ROWCOUNT 、SQL%NOTFOUND
   当系统使用隐式游标时,通过隐式游标的属性了解操作状态和结果、从而控制程序流程*
    begin
         update pandaa set name = '嘎嘎' where plan = 7369;--dml 更新语句
         dbms_output.put_line(SQL%rowcount||'行被更新');--使用隐式游标属性判断已更新行数
         if sql%notfound  --隐式游标属性   判断是否没有任何更新
           then dbms_output.put_line('更新失败');
           end if;
           commit;--自动向数据库提交
           exception 
             when others--其他所有情况
               then dbms_output.put_line(sqlerrm);--打印异常信息
               end;

游标属性
1.%ISOPEN 游标变量是否打开 true、false

declare 
cursor cur
is 
select * from pandaa where plan = 1;
begin
  if not cur%isopen then open cur;--如果游标没有打开则打开游标
    end if;
    if cur%isopen then dbms_output.put_line('游标已经被打开');
    else dbms_output.put_line('游标还没打开');
    end if;
    close cur;
    end;

*–%FOUND属性 fetch 语句获取数据前 、其值为null 即判断是否已经从游标取到数据
–%NOTFOUND属性 没有从游标中取到数据 返回true 与上面相反*

declare 
emp_row pandaa%rowtype;
cursor cur
is
select *from pandaa where plan = 1;
begin 
  open cur;
  if not cur%isopen then open cur; --如果游标没打开  则打开游标
  end if;
  if cur%notfound  is null  then  dbms_output.put_line('%notfound 属性为null');--fetch获取游标数据之前 %notfound为null
  end if;
  loop
    fetch cur  into emp_row;
    exit when cur%notfound; --游标指向没有数据了 跳出循环
    end loop;
    close cur;
    end; 

%rowcount 返回游标取出数据行数

declare 
emp_row pandaa%rowtype;
cursor cur
is
select * from pandaa where plan = 1;
begin
  open cur;
  loop
    fetch cur into emp_row;
    exit when cur%notfound ;
    dbms_output.put_line('当前已从游标提取的行数: '||cur%rowcount||'行');
    end loop;
    close cur;
    end;
执行结果:
当前已从游标提取的行数: 1行
当前已从游标提取的行数: 2行
当前已从游标提取的行数: 3行
当前已从游标提取的行数: 4行
当前已从游标提取的行数: 5行
当前已从游标提取的行数: 6行
当前已从游标提取的行数: 7行
当前已从游标提取的行数: 8行
当前已从游标提取的行数: 9行
当前已从游标提取的行数: 10行
当前已从游标提取的行数: 11行
当前已从游标提取的行数: 12行
当前已从游标提取的行数: 13行

猜你喜欢

转载自blog.csdn.net/fightingitpanda/article/details/79848283