%notfound的理解——oracle預存程序

來源:互聯網
上載者:User
 文檔中的解釋: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。所以以後為了安全期間可以加上是否為空白的判斷

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.