MYSQL游标重复错误的数据

时间:2012-10-22 02:42:13

标签: mysql stored-procedures cursor

我正在尝试第一次创建存储过程和游标,但它的行为并不像预期的那样。一切都很好,但输出数据不正确。如果我手动迭代,我得到我期望的,但不是通过存储过程。

如果您查看下面的输出表,前三个记录是正确的,并且GID对于所有后续条目都是正确的,但是PTS摘要不正确并重复相同的值。

步骤:

DELIMITER //

CREATE PROCEDURE creategamesummary()

BEGIN

DECLARE curdone TINYINT DEFAULT 0;
DECLARE curgid INT;
DECLARE curwk INT;

DECLARE gamescursor CURSOR

FOR

SELECT g1.GID FROM games g1 WHERE g1.SEAS = 2008 AND g1.WK > 4 AND (g1.V = 'BAL' OR g1.H = 'BAL') ORDER BY GID;

DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET curdone=1;

OPEN gamescursor;

REPEAT
    FETCH gamescursor into curgid;

    SET curwk = (SELECT WK FROM games WHERE GID = curgid);

    REPLACE INTO gamesummary
    SELECT
    curgid as GID,
    SUM(t1.PTS) as PTS
FROM
    team t1
WHERE
    t1.GID IN (
    SELECT
    g2.GID
FROM
    games g2
WHERE
    (g2.V = 'BAL' OR
    g2.H = 'BAL') AND
    g2.SEAS = 2008 AND
    g2.WK <= curwk
) AND t1.TNAME = 'BAL';

UNTIL curdone END REPEAT;

    CLOSE gamescursor;

END//

DELIMITER ;

输出表:

GID,PTS
2182,75
2196,78
2212,105
2223,127
2240,127
2259,127
2268,127
2288,127
2306,127
2327,127
2330,127
2346,127
2371,127
2379,127
2381,127
2385,127

1 个答案:

答案 0 :(得分:0)

回答我自己的问题,但我设法将查询重构为以下代码。由于这是我第一次进入游标和存储过程,我仍然会对第一版中出现问题的反馈表示赞赏。

DELIMITER //

CREATE PROCEDURE creategamesummary2()

BEGIN

DECLARE curdone TINYINT DEFAULT 0;
DECLARE curteam varchar(3);

DECLARE teamcursor CURSOR

FOR

SELECT TNAME FROM team WHERE GID in (SELECT GID from games WHERE SEAS = 2008) GROUP BY TNAME;

DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET curdone=1;

OPEN teamcursor;

WHILE NOT curdone DO
    FETCH teamcursor into curteam;

    REPLACE INTO gamesummary2
SELECT
    g1.GID,
    g1.WK,
    curteam AS TNAME,
    (
    SELECT SUM(t1.PTS)
    FROM team t1
    WHERE t1.GID IN (
        SELECT g2.GID
        FROM games g2
        WHERE g2.WK <= g1.WK AND (g2.V = curteam OR g2.H = curteam) AND g2.SEAS = 2008) AND
    t1.TNAME = curteam) AS SUM_PTS
FROM
    games g1
WHERE
    g1.SEAS = 2008 AND
    g1.WK > 4 AND
    (g1.V = curteam OR g1.H = curteam)
GROUP BY GID, WK, curteam;

END WHILE;

    CLOSE teamcursor;

END//

DELIMITER ;