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