declare v_id int;
declare usrcur cursor for select name form t_app_tbl where enable=1;
declare continue handler for NOT FOUND set done=1;
open usrcur;
usrloop :LOOP
fetch usrcur into usr_name;
if done=1 then
leave usrloop;
end if;
select id into v_id from t_mer_tbl where name = usr_name;
loop循环多次时,当前一次循环v_id有值,下一次循环没有记录时,v_id会
赋值为上次一循环的v_id;为什么会这样,正常不是应该是null吗?
这是由于MySQL存储过程的工作方式所致。当第二次循环没有记录时,v_id仍然保留上一次循环的值,因为它仍然存在于存储过程的当前执行上下文中。
可以通过在每次循环后显式将v_id设置为NULL来解决这个问题,即:
declare v_id int;
declare usrcur cursor for select name form t_app_tbl where enable=1;
declare continue handler for NOT FOUND set done=1;
open usrcur;
usrloop :LOOP
fetch usrcur into usr_name;
if done=1 then
leave usrloop;
end if;
select id into v_id from t_mer_tbl where name = usr_name;
-- Add this line
if v_id is null then
set v_id = NULL;
end if;
-- Your remaining code here
这将确保在没有匹配结果时,v_id被设置为NULL而不是保留之前的值。