gpt4 book ai didi

Mysql在存储过程中嵌套while循环

转载 作者:可可西里 更新时间:2023-11-01 07:16:36 26 4
gpt4 key购买 nike

目前我正在处理一个存储过程,其中我在另一个 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。我在努力。

最佳答案

这是因为在外层 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 ;

关于Mysql在存储过程中嵌套while循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17259860/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com