循环结构 while and repeat
1、WHILE 结构
(1)语法
[标签:] WHILE 循环条件 DO
循环体;
END WHILE [标签];
(2)案例:没有使用标签
CREATE PROCEDURE loop_pro1(IN mycount INT)
BEGIN
DECLARE i INT DEFAULT 1;
WHILE i<=mycount DO
SELECT i;
SET i=i+1;
END WHILE;
END $
CALL lopp_pro1(10) $
(3)案例:使用了标签
CREATE PROCEDURE loop_pro2(IN mycount INT)
BEGIN
DECLARE i INT DEFAULT 1;
a:WHILE i<=mycount DO
SELECT i;
SET i=i+1;
END WHILE a;
END $
CALL lopp_pro2(10) $
(4)案例:使用标签+leave(break)
CREATE PROCEDURE loop_pro3(IN mycount INT,OUT result INT)
BEGIN
DECLARE i INT DEFAULT 1;
DECLARE SUM INT DEFAULT 0;
a:WHILE i<=mycount DO
SET SUM = SUM+i;
IF SUM>20 THEN LEAVE a;
END IF;
SET i=i+1;
END WHILE a;
SELECT SUM INTO result;
END $
CALL loop_pro3(10,@r) $
SELECT @r $
2、REPEAT结构
(1)语法
[标签:]REPEAT
循环体;
UNTIL 结束条件 END REPEAT [标签];
(2)案例:无标签
CREATE PROCEDURE loop_pro4(IN mycount INT)
BEGIN
DECLARE i INT DEFAULT 1;
REPEAT
SELECT i;
SET i=i+1;
UNTIL i>mycount END REPEAT;
END $
CALL loop_pro4(4) $
(3)案例:有标签,没有使用leave
CREATE PROCEDURE loop_pro5(IN mycount INT)
BEGIN
DECLARE i INT DEFAULT 1;
a:REPEAT
SELECT i;
SET i=i+1;
UNTIL i>mycount END REPEAT a;
END $
CALL loop_pro5(4) $
(4)案例:有标签,使用leave
CREATE PROCEDURE loop_pro6(IN mycount INT)
BEGIN
DECLARE i INT DEFAULT 1;
a:REPEAT
SELECT i;
IF i=2 THEN LEAVE a;
END IF;
SET i=i+1;
UNTIL i>mycount END REPEAT a;
END $
CALL loop_pro6(10)
3、while 和 repeat 的对比
执行顺序 循环条件 语法不同
WHILE 先判断后执行 循环成立的条件 WHILE关键字
REPEAT 先执行后判断 循环结束的条件 REPEAT关键字
网友评论