如何在 MySQL 存储过程中使用 FOR LOOP?


以下是 MySQL 存储过程中使用 FOR LOOP 的语法 −

delimiter //
CREATE procedure yourProcedureName()
wholeblock:BEGIN
   DECLARE anyVariableName1 INT ;
   Declare anyVariableName3 int;
   DECLARE anyVariableName2 VARCHAR(255);
   SET anyVariableName1 =1 ;
   SET anyVariableName3 =10;
   SET anyVariableName2 = '';
loop_label: FORLOOP
   IF anyVariableName1 > anyVariableName3 THEN
      LEAVE loop_label;
   END IF;
   SET anyVariableName2 = CONCAT(anyVariableName2 ,anyVariableName1 ,',');
   SET anyVariableName1 = anyVariableName1 + 1;
   ITERATE loop_label;
   END FORLOOP;
SELECT anyVariableName2;
END
//

现在你可以实现上述语法。for 循环查询如下 −

mysql> delimiter //
mysql> CREATE procedure ForLoop()
   -> wholeblock:BEGIN
   -> DECLARE start INT ;
   -> Declare maxLimit int;
   -> DECLARE result VARCHAR(255);
   -> SET start =1 ;
   -> SET maxLimit=10;
   -> SET result = '';
   -> loop_label: LOOP
   -> IF start > 10 THEN
   -> LEAVE loop_label;
   -> END IF;
   -> SET result = CONCAT(result,start,',');
   -> SET start = start + 1;
   -> ITERATE loop_label;   
   -> END LOOP;
   -> SELECT result;
   -> END
   -> //
Query OK, 0 rows affected (0.37 sec)
mysql> delimiter ;

以上是循环语句,打印 1 到 10,即以 1、2、3、4、.....10 的形式。使用 CALL 命令调用存储过程。语法如下 −

call yourStoredProcedureName();

调用查询如下 −

mysql> call ForLoop();

输出

+-----------------------+
| result                |
+-----------------------+
| 1,2,3,4,5,6,7,8,9,10, |
+-----------------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.01 sec)

更新日期: 30-Jul-2019

3K+ 浏览

启动你的 职业

完成课程即可获得认证

立即开始
广告