0

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

如果您查看下面的输出表,前三个记录是正确的,并且所有后续条目的 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
4

1 回答 1

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 ;
于 2012-10-22T03:45:34.823 回答