我第一次尝试创建一个存储过程和一个游标,但它的行为并不像预期的那样。一切都执行得很好,但输出数据不正确。如果我手动迭代,我会得到我所期望的,但不是通过存储过程。
如果您查看下面的输出表,前三个记录是正确的,并且所有后续条目的 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