您好,欢迎访问一九零五行业门户网

MYSQL嵌套游标产生混乱的解决方法及注意地方_MySQL

bitscn.com
mysql嵌套游标产生混乱的解决方法及注意地方 1. 在编写存储过程中, 有时会处理些较复杂的数据, 用到多个游标, 并且嵌套使用,如果控制不好,在子层游标记录处理完后,  上层游标也会捕获not found异常, 并改变标示值. 产生数据混乱.例: [sql] begin    declare name_stop int default 0;       declare        cur_name cursor for select        name      from mytable;          declare continue handler for not found set name_stop =1;          open cur_name;        fetch cur_name into v_name;        start transaction;             begin                declare ext_stop int default 0;          declare cur_ext            cursor for select           propertyid          from propertys;          declare continue handler for not found set ext_stop =1;                  ..............................  当子层cur_ext游标记录处理完后, 会抛出not found, 不仅影响自身, 而且上层游标也会受影响, name_stop 会变成1, 这时就会跳出循环, 不再执行.    
解决的办法是加入标记块放置复合语句中,如: block1:begin....end block1;限制作用范围,  这样就能解决各游标间的干扰. 2. 在实际使用中,  可能会采用select ... into ...语句进行赋值,  但是如果没有找到记录, 是不会把null值赋给相应变量, 而是抛出not found.如果采用了游标, 这将会影响正常使用.所以,  最好把select into语句放入单独的复合语句, 并加入标记块,注意, 需要加入一个临时的handler,  如果没有handler捕获, 仍会跳入上层, 影响游标.正确使用方法, 如下所示: [sql] block4: begin     declare temp_a int default 0;     declare continue handler for not found set temp_a = -1;     select account into v_exist_account from t_user where account = v_account limit 1;  end block4;       如果v_exist_account有后续业务处理, 记得处理完后要清空值.   摘自 hxx688的专栏 bitscn.com
其它类似信息

推荐信息