關於Oracle游標的一些專案中遇到的邏輯問題

2021-09-30 23:21:25 字數 1875 閱讀 3650

今天 在專案中看乙個儲存過程的時候,發現同事寫的之前的有些邏輯錯誤,可能這個錯誤比較典型吧 拿出來分享一下,不使用公司的資料庫,所以在自己的機子上模擬了一下這個場景。ok

首先,就是2個表,

表temp1,包括id1,val1,2個字段,

表temp2,包括id2,val2 2個字段。

首先,情景大致是這樣的,2個表的id是有關聯的,就是把temp2中包含的temp1的id的資料,在temp1中把val1都設定為1,不包含的設定為0.

首先,發一下之前錯誤的儲存過程。

create or replace procedure mysdtest

as

cursor te_v1 is

select id1,val1 from temp1;

cursor te_v2 is

select id2,val2 from temp2;

v1_t te_v1%rowtype;

v2_t te_v2%rowtype;

begin

open te_v1;

loop

fetch te_v1 into v1_t;

exit when te_v1%notfound;

open te_v2;

loop

fetch te_v2 into v2_t;

exit when te_v2%notfound;

if v1_t.id1=v2_t.id2

then update temp1 set val1='1' where id1=v1_t.id1;

else

update temp1 set val1='0' where id1=v1_t.id1;

end if;

end loop;

close te_v2;

end loop;

close te_v1;

end;

這樣寫邏輯是存在問題的,2層迴圈,結果就會發現都是0,仔細讀一下程式就會發現問題

比如說有乙個值 t1 在表temp1中有值,應該更新val1為1,但是遍歷到下乙個t2時,此時t1不符合,然後就執行else 那麼t1的val1就又變回了0,所以,程式執行完,都執行了else裡面的,當然就錯了。

正確的寫法很多種,這裡我就以設定帶引數的游標為例,將2個游標建立關係,再進行遍歷就不會出現問題。

如下:create or replace procedure myt

as

cursor te_v1 is

select id1,val1 from temp1;

cursor te_v2(idv2 varchar2) is

select count(*) from temp2 where id2=idv2;

v1_t te_v1%rowtype;

numv varchar2(2);

begin

open te_v1;

loop

fetch te_v1 into v1_t;

exit when te_v1%notfound;

open te_v2(v1_t.id1);

fetch te_v2 into numv;

if numv=0

then

update temp1 set val1='0' where id1=v1_t.id1;

else

update temp1 set val1='1' where id1=v1_t.id1;

end if;

close te_v2;

end loop;

close te_v1;

end;

ok,這種問題我們應該注意到

游標的一些操作總結

ie下的range操作比mozilla下強很多,這裡只討論ie下的操作。這裡選介紹幾個游標定位的特點 1.游標不變 直接obj.focus 游標會返回之前的位置,即位置不變 2.游標在最前 var r obj.createtextrange r.collapse r.select 用這個方法可以使游...

js中游標的一些操作

有時候我們需要操作input,textarera中的游標,現在列舉出一些js例子 首先看ie ie中的物件是這個 createtextrange var range el.createtextrange range.moveend character el.value.length range.mo...

關於目標的一些感想

我的性格比較內向,但是我希望改變這一現狀,曾經試圖通過專門的有針對性的實踐去鍛鍊自己。但是,過程是痛苦的,最後還是輸給了自己的性格。有些時候感慨,江山易改本性難移,就這樣了吧。後來又想,周杰倫曾經性格也很內向啊,開出道的時候,很害羞,話不會說。現在則在 面前很自然,很成熟。這是為什麼呢?想來想去,我...