目前我正在处理一个存储过程,其中我在另一个while循环下使用一个while循环。但我没有得到预期的结果。最外层的循环只是迭代一次。
我正在尝试使用代码。
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。我正在努力。
答案 0 :(得分:10)
这是因为在外部while循环的第一次迭代之后,second_while_start
的值已经是second_while_count
,因此内部循环不会执行,因为second_while_start
不再小于{{ 1}}。
要获得“预期结果”,您需要重置second_while_start。
second_while_count