zoukankan      html  css  js  c++  java
  • %notfound的理解——oracle存储过程 .

    文档中的解释:It returns TRUE if an INSERT, UPDATE, or DELETE statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it returns FALSE.
    这个解释更加精妙:
    %NOTFOUND is the logical opposite of %FOUND. %NOTFOUND yields FALSE if the last fetch returned a row, or TRUE if the last fetch failed to return a row
    错误的例子:
    tableA
    id  name
    1   a
    2   b

    declare
    cursor v_cur is select name from tableA;

    n varchar2(10);
    begin
    open v_cur;
    loop
    exit when v_cur%notfound;
    fetch v_cur into n;

    dbms_output.put_line(n);

    close v_cur;
    end loop;

    end;


    执行上面的语句,结果为:
    a
    b
    b
    发现最后一条记录被打印了两次。原因是%notfound是判断最后一次fetch的结果,把bfetch到变量n中之后再执行exit when %notfound判断得到的是false的记过,也就是说是有返回行的,所以判断通过,再此执行了打印语句。
    发现了另一个疑问:
    把a,b都fetch之后按理说游标已经空了,那么第三次应该是fetch的空值,为什么打印出来的还是b呢??
    因为fetch..into语句末尾不会修改into变量后面的值。就像select..into如果没有数据会报异常,但是不会把into后面的变量置为空
    再写一段代码

    declare
    cursor v_cur is select name from tableA where name = 'c';

    n varchar2(10);
    begin
    open v_cur;
    loop
    exit when v_cur%notfound;

    n:='hehe'
    fetch v_cur into n;

    dbms_output.put_line(n);

    close v_cur;
    end loop;

    end;
    执行代码的结果:
    hehe
    疑问:游标是空游标,也就是说游标在打开的时候就没有指向任何的值。但为什么
    exit when v_cur%notfound;这条语句还通过了呢??
    oracle文档的解释:

    Before the first fetch, %NOTFOUND returns NULL. If FETCH never executes successfully, the loop is never exited, because the EXIT WHEN statement executes only if its WHEN condition is true. To be safe, you might want to use the following EXIT statement instead:

    EXIT WHEN c1%NOTFOUND OR c1%NOTFOUND IS NULL;

    也就是说v_cur%notfound有三种状态,true,false,null。所以以后为了安全期间可以加上是否为空的判断

  • 相关阅读:
    ubuntu16.04安装破解pycharm
    python解压,压缩,以及存数据库的相关操作
    cocoapods Error
    swift项目导入OC框架
    实现全屏滑动返回效果
    Storyboard & XIB 自己的理解
    View & Controller 一些方法的执行顺序
    Touch ID 实现
    Apple Pay 初探
    ReactiveCocoa学习
  • 原文地址:https://www.cnblogs.com/dingyingsi/p/3358682.html
Copyright © 2011-2022 走看看