MYSQL存储过程问题

时间:2013-08-07 16:12:41

标签: mysql stored-procedures cursor

我是第一次编写MySQL存储过程,我遇到了一个问题 - 我认为使用Handler Code。基本上,我希望这段代码更新pps_users表中的所有行,但由于某种原因,我只获取了两行后才处理处理程序的“已完成条件”。

我使用REPEAT语法尝试了同样的事情并获得了相同的结果。如果我只是运行游标查询我正确地获得了我期望的10,000条记录,但是当我按原样运行整个事情时,我只在1或2条记录之后点击完成的代码。

DELIMITER $$

CREATE DEFINER=`root`@`localhost` PROCEDURE `changeNFLFavTeams`()
BEGIN
    DECLARE favNFLTeam varchar(100) DEFAULT "";    
    DECLARE favNCAATeam varchar(100) DEFAULT "";    
    DECLARE v_finished INTEGER DEFAULT 0;
    DECLARE user_id bigint(20);
    DECLARE fullNameOfTeam varchar(100) DEFAULT ""; 
    DECLARE update_favs CURSOR FOR select id, favorite_nfl_team from pps_users WHERE favorite_nfl_team is not null;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finished = 1;    
    OPEN update_favs;


    updaterecord: LOOP
    FETCH update_favs INTO user_id, favNFLTeam;

        select user_id, favNFLTeam as "Test";

        if v_finished = 1
        then
            select "finished" as "finished";
            LEAVE updaterecord;
        end if;

        select full_name into fullNameOfTeam
                                from teams t 
                                inner join display_names dt on dt.entity_id = t.id 
                                and dt.entity_type = 'teams' 
                                and dt.first_name = favNFLTeam
                                and team_key like 'l.nfl.com%' LIMIT 1;

    select user_id, fullNameOfTeam AS "BeforeUpdate";

            IF fullNameOfTeam != ''
            THEN
               -- here for whatever_transformation_may_be_desired
            -- Find the Full name for the record they chose
                UPDATE pps_users p
                SET favorite_nfl_team = fullNameOfTeam
               WHERE user_id = p.id;
            ELSE
                SELECT 'A' AS 'A'; -- no op
            END IF;  


  end loop updaterecord;

  CLOSE update_favs;

END

1 个答案:

答案 0 :(得分:0)

这是因为如果您的SELECT full_name到fullNameOfTeam ...查询没有返回任何行,那么它会将v_finished设置为1.显然,这很早就发生了,并强制退出主循环。

关键是要意识到NOT FOUND的CONTINUE HANDLER不仅适用于光标。

您应该将辅助查询放入其自己的CONTINUE处理程序的BEGIN..END块中,或者(更简单地)将SELECT full_name设置为fullNameOfTeam ...语句后设置v_finished = 0。