MySQL 存储过程 - 循环语句

WHILE 循环

WHILE 语句的语法如下:

WHILE expression DO
   statements
END WHILE 

示例

DROP PROCEDURE IF EXISTS test;
DElIMITER $$
CREATE PROCEDURE test(IN startNumber int, IN endNumber int)
    BEGIN
        DECLARE num int DEFAULT 0;
        WHILE startNumber <= endNumber DO
            set num = num + 2;
            set startNumber = startNumber + 1;
        END WHILE;
        SELECT num;
    END $$
DElIMITER;

CALL test(1, 10);

REPEAT 循环

REPEAT 循环语句的语法如下:

REPEAT
 statements;
UNTIL expression
END REPEAT 

示例

DROP PROCEDURE IF EXISTS test;
DElIMITER $$
CREATE PROCEDURE test(IN startNumber int, IN endNumber int)
    BEGIN
        DECLARE num int DEFAULT 0;
        WHILE startNumber <= endNumber DO
            set num = num + 2;
            set startNumber = startNumber + 1;
        END WHILE;
        SELECT num;
    END $$
DElIMITER;

CALL test(1, 10);