7

目前我正在研究一个存储过程,其中我在另一个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。我在尝试。

4

1 回答 1

14

这是因为在外部 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 ;
于 2013-06-23T10:53:53.363 回答