mysql-循环(while 、repeat、loop)

发布时间 2023-12-28 23:06:04作者: 2024-DBA

--while

DELIMITER $$
CREATE PROCEDURE p7(IN n INT)
BEGIN
DECLARE total INT DEFAULT 0;
WHILE n>0 DO
SET total:=total+n;
SET n:=n-1;
END WHILE;
SELECT total;
END$$
CALL p7(2)

--repeat

DROP PROCEDURE IF EXISTS p8
DELIMITER $$
CREATE PROCEDURE p8(IN n INT)
BEGIN
DECLARE total INT DEFAULT 0;
REPEAT
SET total:=total+n;
SET n:=n-1 ;
UNTIL n<0
END REPEAT;
SELECT total;
END$$
CALL p8(4)

--loop
计算从1累加到n的值,n为传入的参数
计算1到n之间偶数累加的值,n为传入的参数
DROP PROCEDURE IF EXISTS p9
DELIMITER $$
CREATE PROCEDURE p9(IN n INT)
BEGIN
DECLARE total INT DEFAULT 0;
SUM:LOOP
IF n<=0 THEN
LEAVE SUM;
END IF;

IF n%2=1 THEN
SET n:=n-1;
ITERATE SUM;
END IF;
SET total:=total+n;
SET n:=n-1;
SELECT n;
END LOOP SUM;
SELECT total;
END$$
CALL p9(4)