MySQL stored procedure cursor LOOP

I generally like to add a row number (row_number(0)) to the table and loop according to the row number. This is the standard way to use cursors. The method of looping after adding a row number to the table is more common in Oracle, SQL, and MySQL. It is used in large quantities. You can also add an index to the row number when collecting data. It is better to use an index in the database.

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

Guess you like

Origin blog.csdn.net/qq_34677276/article/details/131930859
Recommended