当前位置:Gxlcms > 数据库问题 > oracle中游标的使用

oracle中游标的使用

时间:2021-07-01 10:21:17 帮助过:20人阅读

    3.SQL%NOTFOUND    布尔型 值为true表示插入、删除、更新或单行查询操作失败。

    4.SQL%ISOPEN  布尔型 DML执行过程中为真,结束后为假  

三,游标的使用

    隐式游标的使用主要就是以上的四种属性的使用,使用它们来进行一些流程控制。

    显示游标的声明和使用

      cursor cursor_name[ 参数1 参数类型,参数2,参数类型...]  is select 语句;

    游标的使用步骤:

      1.声明一个游标

      2.打开游标 open 游标名(参数1,参数2..);

      3.使用循环遍历游标,从游标中取值。fetch 游标名 into 变量名,循环的退出条件是 游标名%notfound;

      4.关闭游标 close 游标名;

    游标的遍历(两种方式)

      1.使用loop循环遍历

        例如 :

            declare
              cursor outemp is  select * from emp;
              ouem emp%rowtype;//也可以是%type,但是必须和表中的类型一致。
            begin
              open outemp;
              loop
                fetch outemp into ouem;
                exit when outemp%notfound;//退出条件
                dbms_output.put_line(ouem.ename || ‘ ‘ ||ouem.sal);
              end loop;
              close outemp;
            end;

      2.使用for循环遍历游标

        例如:

            declare

              cursor outfor is  select * from emp;
            
begin
              for vrow in outfor loop
                dbms_output.put_line(vrow.ename || ‘ ‘ || vrow.sal);
              end loop;
            end;

      使用for循环遍历游标的好处:1.不用声明额外的变量,2.不用打开和关闭游标,3.写法简单。

    系统引用游标

      1. 声明游标 : 游标名 sys_refcursor
      2. 打开游标: open 游标名 for select语句;
      3. 从游标中取数据
      4. 关闭游标

     例如:--输出员工表中所有的员工姓名和工资

        declare
          vrows sys_refcursor;
          vrow emp%rowtype;
        begin
          
open vrows for select * from emp;
          loop
          
  fetch vrows into vrow;
            exit when vrows%notfound;
            dbms_output.put_line(‘姓名:‘||vrow.ename ||‘ 工资: ‘ || vrow.sal);
          end loop;
          close vrows;
        end;
以上就是游标的基础,使用游标时一定要记得关闭游标,还有就是在定义变量时需要注意定义的类型必须要和表中的字段类型一致,否则会出错。

详情参见:https://blog.csdn.net/liyong199012/article/details/8948952

oracle中游标的使用

标签:sop   用户   能力   open   upd   etc   log   out   方法   

人气教程排行