MySQL 存储过程 游标 LOOP

我一般喜欢给表加了行号(row_number(0),按行号去循环,此种是标准的游标使用方法,也无可厚非,表加了行号去循环的方法,在Oracle,SQL,MySQL比较通用,大量数据时也可以给行号加索引,数据库使用索引较优。

CREATE DEFINER = 'root'@'localhost'
PROCEDURE LoopByLine()
BEGIN
    DECLARE MyStation char(20);
    DECLARE N int DEFAULT 0;
    DECLARE MyID int DEFAULT 0;
    DECLARE MyScore dec(5,1);
    DECLARE MyTotalScore dec(5,1);
    DECLARE done INT DEFAULT FALSE;
    DECLARE MyCursor CURSOR FOR
    SELECT ID,Station,Score FROM StationScore;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    set MyTotalScore=0;
    OPEN MyCursor;
    read_loop:LOOP 
        FETCH MyCursor INTO MyID,MyStation,MyScore;
        IF done THEN
           LEAVE read_loop;
        END IF;
        set MyTotalScore=MyTotalScore+MyScore;
        set N=N+1;
    END LOOP;
    CLOSE MyCursor;
    SELECT MyTotalScore,N;
END

你可能感兴趣的:(mysql,数据库)