MySQL过程循环在一次迭代后停止

MySQL过程循环在一次迭代后停止,mysql,cursor,procedure,Mysql,Cursor,Procedure,我正在处理一个MySQL过程,该过程创建我的一个表的摘要。该过程检索数据集,并使用游标在其中循环。对于循环的每次迭代,过程都会更新另一个表。我遇到的问题是循环在一次迭代后结束,尽管我知道我正在运行的查询检索多行 BEGIN # Variable declaration section omitted for brevity DECLARE cur CURSOR FOR SELECT t.result_id, t.athlete_id, t.`first`, t.mid

我正在处理一个MySQL过程,该过程创建我的一个表的摘要。该过程检索数据集,并使用游标在其中循环。对于循环的每次迭代,过程都会更新另一个表。我遇到的问题是循环在一次迭代后结束,尽管我知道我正在运行的查询检索多行

BEGIN
  # Variable declaration section omitted for brevity


  DECLARE cur CURSOR FOR SELECT
    t.result_id,
    t.athlete_id, t.`first`, t.middle, `last`, t.pref, t.birth,t.uss,
    t.club_id,t.code,t.club_name,
    t.meet_name,t.meet_id,t.`start`,t.`end`,
    MIN(t.time) as time,t.age,t.type
     FROM sometable t GROUP BY club_id ORDER BY time asc,t.start desc,club_id;

  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
  OPEN cur;

  read_loop: LOOP

    FETCH cur INTO result_id,athlete_id, first_name, middle, last_name, pref, birth,uss,
    club_id,club_code,club_name,
    meet_name,meet_id,start_date,end_date,
    result_time,age,type;

    IF done=1 THEN
      LEAVE read_loop;
    END IF;


    SET last_time = result_time;

    INSERT INTO toptimes(`result_id`,`club_id`,`agegroup`,`sex`,`distance`,`course`,`stroke`,`data`,`published`)
    VALUES(result_id,club_id,AgeGroupID,sex,distance,course,stroke,json,0);

  END LOOP read_loop;
  CLOSE cur;
END

我不清楚问题出在哪里。当我手动运行select查询时,我会返回几行。在循环中运行insert语句是否有问题?

我觉得您的代码块不错

你怎么知道它只运行一次迭代(我没有看到任何迭代) 打印或选择语句(用于调试)? 执行存储过程时是否出现错误

我试图用“sakila”数据库(mysql示例数据库)复制类似的代码。它工作得很好。如果这个sql代码示例对您有帮助,请检查它

DROP PROCEDURE IF EXISTS usp_select_dummy_data ;

DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE usp_select_dummy_data()
BEGIN
-- Declare your variables
    Declare _var_actor_id int default 0;
    DECLARE _var_film_id int default 0;

-- Declare variable used for cursor and loop control
    DECLARE done int;
    DECLARE loop_counter INT DEFAULT 0;

-- Declare the cursor
     DECLARE cur CURSOR FOR
        SELECT
             actor_id, film_id
        FROM film_actor;

-- Declare handlers
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

-- Open the cursor 
   OPEN cur ;

-- Start the loop
  read_loop: LOOP
    FETCH  cur
      INTO  _var_actor_id, _var_film_id ;

    -- break out of the loop if
    -- 1. if there is no rows or
    -- 2.  we've processed them all
     IF done = 1 THEN
       CLOSE cur ;
             LEAVE read_loop ;
      END IF;

    -- Count the number of times looped
       SET loop_counter = loop_counter + 1 ;

    END LOOP read_loop ;

-- print the loop count
 select loop_counter;
END 

看看你的代码,我看不出有什么理由在你可以插入的时候使用循环。。在一个查询中选择行。是否需要一些其他代码,但您没有在此处显示?请尝试移动
DECLARE CONTINUE HANDLER FOR not FOUND SET done=1
循环之后
。谢谢@DavidSoussan,我将代码更改为使用INSERT。。选择一个有效的方法。它还减少了程序运行的时间。不知道为什么我的代码没有在所有记录中循环。但最好知道在游标内部可以进行更新。最后,我在关于使用insert-select的评论中使用了这个建议。这对我来说很有效,而且完成的时间也少了很多。@Raushan,我的循环计数器是1。真奇怪。这里有什么解决办法吗?