2013-06-23 97 views
4

當前我正在使用一個存儲過程,其中我在另一個while循環下使用了一個while循環。但我沒有得到預期的結果。最外層的循環只是一次迭代。Mysql在循環中嵌套在存儲過程中

我想下面的代碼。

DELIMITER $$ 

DROP PROCEDURE IF EXISTS `First_Sp` $$ 
CREATE DEFINER=`root`@`localhost` PROCEDURE `First_Sp`() 
BEGIN 

    DECLARE first_while_start INTEGER DEFAULT 1; 
    DECLARE second_while_start INTEGER DEFAULT 1; 
    DECLARE first_while_count INTEGER DEFAULT 3; 
    DECLARE second_while_count INTEGER DEFAULT 3; 

    WHILE first_while_start < first_while_count 
    DO 
    WHILE second_while_start < second_while_count 
    DO 
     SELECT concat(first_while_start,' - ',second_while_start) as result; 
     SET second_while_start = second_while_start + 1; 
    END WHILE; 
    SET first_while_start = first_while_start + 1; 
    END WHILE; 
END $$ 

DELIMITER ; 

結果:

mysql> call first_sp(); 
+--------+ 
| result | 
+--------+ 
| 1 - 1 | 
+--------+ 
1 row in set (0.00 sec) 

+--------+ 
| result | 
+--------+ 
| 1 - 2 | 
+--------+ 
1 row in set (0.00 sec) 

Query OK, 0 rows affected (0.00 sec). 

我也試圖重複循環。但仍然沒有運氣。

DELIMITER $$ 

DROP PROCEDURE IF EXISTS `First_Sp` $$ 
CREATE DEFINER=`root`@`localhost` PROCEDURE `First_Sp`() 
BEGIN 

    DECLARE first_while_start INTEGER DEFAULT 1; 
    DECLARE second_while_start INTEGER DEFAULT 1; 
    DECLARE first_while_count INTEGER DEFAULT 3; 
    DECLARE second_while_count INTEGER DEFAULT 3; 

    REPEAT 
    WHILE second_while_start < second_while_count 
    DO 
     SELECT concat(first_while_start,' - ',second_while_start) as result; 
     SET second_while_start = second_while_start + 1; 
    END WHILE; 
    SET first_while_start = first_while_start + 1; 
    UNTIL first_while_start < first_while_count 
    END REPEAT; 

END $$ 

DELIMITER ; 

我不是很多的SQL Developer。我在嘗試。

回答

7

這是因爲外while循環的second_while_start值已經second_while_count的第一次迭代之後從而內環不執行如second_while_start不再小於second_while_count

要獲得您的「預期結果」,您需要重置second_while_start。

DELIMITER $$ 

DROP PROCEDURE IF EXISTS `First_Sp` $$ 
CREATE DEFINER=`root`@`localhost` PROCEDURE `First_Sp`() 
BEGIN 

    DECLARE first_while_start INTEGER DEFAULT 1; 
    DECLARE second_while_start INTEGER DEFAULT 1; 
    DECLARE first_while_count INTEGER DEFAULT 3; 
    DECLARE second_while_count INTEGER DEFAULT 3; 

    WHILE first_while_start < first_while_count 
    DO 
    WHILE second_while_start < second_while_count 
    DO 
     SELECT concat(first_while_start,' - ',second_while_start) as result; 
     SET second_while_start = second_while_start + 1; 
    END WHILE; 
    SET first_while_start = first_while_start + 1; 
    /*here comes the important line:*/ 
    SET second_while_start = 1; 
    END WHILE; 
END $$ 

DELIMITER ;