Mysql之循環語句 ************************** LOOP ************************** 語法: Java代碼 [begin_label:] LOOP statement_list END LOOP [end_label] 實例: Java代碼 DELIMITER$$ CREATE PROCEDURE pro_loop(p1 INT) BEGIN label1: LOOP SET p1 = p1 + 1; IF p1 < 10 THEN SELECT p1 AS result; ITERATE label1; END IF; SELECT 'END IF' AS result; LEAVE label1; END LOOP label1; SET @x = p1; SELECT @x as result; END$$ 調用: call pro_loop(8); 輸出: 9 , END IF , 10; 說明: ITERATE label1 : 繼續循環label1 LEAVE label1 : 退出label1循環 注: 當把打印代碼放到ITERATE , LEAVE 後,不能輸出; ************************** WHILE ************************** 語法: Java代碼 [begin_label:] WHILE search_condition DO statement_list END WHILE [end_label] 實例: Java代碼 DELIMITER$$ DROP PROCEDURE IF EXISTS pro_while$$ CREATE PROCEDURE pro_while ( i INT ) BEGIN DECLARE j INT DEFAULT 1; WHILE j < i DO SELECT j AS result; SET j = j + 1; END WHILE; END$$ 調用:call pro_while(3); 輸出:1 , 2 ************************** REPEAT ************************** 語法: Java代碼 [begin_label:] REPEAT statement_list UNTIL search_condition END REPEAT [end_label] 實例: Java代碼 DELIMITER$$ DROP PROCEDURE IF EXISTS pro_repeat$$ CREATE PROCEDURE pro_repeat(p1 INT) BEGIN SET @X = 0; REPEAT SELECT @X AS result; SET @X = @X + 1; UNTIL @X > p1 END REPEAT; END$$ 調用:call pro_repeat(2); 輸出:0 , 1 , 2 說明: 先循環一次,再判斷,直到@X > p1 就結束循環