while循环
[begin_label:] WHILE search_condition
DO statement_list;
END WHILE [end_label];
先判断条件是否成立,成立就执行SQL语句,当条件不成立就退出
1.条件,一定避免死循环!!!!
2.SQL语句体
3.程序体里面,需要对条件变量进行处理------条件需要变化,不然就会是死循环
repeat循环
[begin_label:] REPEAT
statement_list;
UNTIL search_condition END REPEAT [end_label];
先执行SQL语句,在判断条件,当until条件成立就结束循环
loop循环(往往跟着if......end if)
在循环之间必须有退出(leave)
没有隐藏的判断条件
leave(跳出整个循环体)
LEAVE can be used within BEGIN ... END or loop constructs (LOOP, REPEAT, WHILE).
举例:
DELIMITER $$
CREATE PROCEDURE small_exit(OUT p1 INT,OUT p2 INT)
BEGIN
SET p1=1;
SET p2=2;
block1:BEGIN
LEAVE block1;------------直接退出block1,不会去执行赋值的语句
SET p2=3;
END block1;
SET p1=4;
END $$
DELIMITER ;
CALL small_exit(@p1,@p2);
SELECT @p1;
SELECT @p2;
mysql> SELECT @p1;
+------+
| @p1 |
+------+
| 4 |
+------+
1 row in set (0.00 sec)
mysql> SELECT @p2;
+------+
| @p2 |
+------+
| 2 |
+------+
ITERATE(跳出本次循环,继续下次循环)
ITERATE can appear only within LOOP, REPEAT, and WHILE statements. ITERATE means “start the loop again.”
但是需要结束整个循环,还需要leave
例题:
1.输入任意一个数值,作为累计的起始值;
2.输入一个数值,表示累加的次数
3.要求:
从该起始值开始连续累加,累加的次数为输入的第二个变量;累加的数值为随机生成的任意值;
使用repeat实现;
4.举例:
call proc_name(123,3);
累加的和为:123+随机数1+随机数2+随机数3
DROP PROCEDURE IF EXISTS sum2_proc;
DELIMITER $$
CREATE PROCEDURE sum2_proc(IN zhong_num FLOAT(6),IN act_num INT)
BEGIN
DECLARE i INT DEFAULT 0; -- 声明变量
WHILE i<4 -- 循环执行条件判断
DO
SET i=i+1;
SET zhong_num=zhong_num+RAND();
END WHILE;
SELECT zhong_num,i;
END $$
DELIMITER ;
CALL sum2_proc(123,4);
DROP PROCEDURE IF EXISTS sum1_proc;
DELIMITER $$
CREATE PROCEDURE sum1_proc(IN zhong_num FLOAT,IN act_num INT)
BEGIN
DECLARE i INT DEFAULT 0;
-- 声明变量
REPEAT
SET i=i+1;
SET zhong_num=zhong_num+RAND();
UNTIL i=act_num -- 退出循环条件
END REPEAT;
SELECT zhong_num,i;
END $$
DELIMITER ;
CALL sum1_proc(123,4);