关于Oracle游标的一些项目中遇到的逻辑问题

今天 在项目中看一个存储过程的时候,发现同事写的之前的有些逻辑错误,可能这个错误比较典型吧 拿出来分享一下,不使用公司的数据库,所以在自己的机子上模拟了一下这个场景。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,这种问题我们应该注意到

猜你喜欢

转载自hanyingjun318.iteye.com/blog/2084137