declare cur_service_type cursor for select st_name,st_id from service_type;
declare continue handler for not found set stopFlag1=1;
open cur_service_type;
  repeat
    fetch cur_service_type into type_name,type_id;
    select type_name;
  until stopFlag1=1 end repeat;
close cur_service_type;service_type这个表里明明只有两条
怎么用select输出,有三条记录
最后两条是重复的?

解决方案 »

  1.   

    repeat 是先执行,后判断,最后一次FETCH已经使stopFlag1=1,但还是要先执行select type_name;然后才判断 until stopFlag1=1 end repeat; 所以最后一次会重复。 换成while 试一下。MySQL官方文档 http://dev.mysql.com/doc/refman/5.1/zh/index.html
      

  2.   

    应该在select type_name前后加上条件判断的。因为fetch完以后,@stopFlag值可能为1,但你依然把它的值取出来了。多了一次执行。e.g.mysql> CREATE PROCEDURE handlerdemo ()
        -> begin
        -> declare type_name varchar(32);
        -> declare type_id int;
        -> declare cur_service_type cursor for select st_name,st_id from service_type;
        -> declare continue handler for not found set @stopFlag1=1;
        -> open cur_service_type;
        ->   set @stopFlag1 = 0;
        ->   repeat
        ->     fetch cur_service_type into type_name,type_id;
        ->     if @stopFlag1 != 1 then
        ->       select type_name;
        ->     end if;
        ->   until @stopFlag1=1 end repeat;
        -> close cur_service_type;
        -> end;
        -> //
    Query OK, 0 rows affected (0.00 sec)mysql> call handlerdemo(); //
    +-----------+
    | type_name |
    +-----------+
    | aaa       |
    +-----------+
    1 row in set (0.00 sec)+-----------+
    | type_name |
    +-----------+
    | bbb       |
    +-----------+
    1 row in set (0.00 sec)Query OK, 0 rows affected (0.00 sec)
      

  3.   

    感觉mysql这个流程控制很原始,还是半自动的
      

  4.   

    还好了。还是你的代码里头有问题啊。按道理,第一次fetch操作应该放到循环外头。