Maison  >  Article  >  base de données  >  Comment utiliser FOR LOOP dans une procédure stockée MySQL ?

Comment utiliser FOR LOOP dans une procédure stockée MySQL ?

PHPz
PHPzavant
2023-08-29 10:17:09963parcourir

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

Ce qui suit est la syntaxe d'utilisation de FOR LOOP dans une procédure stockée MySQL -

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
//

Vous pouvez maintenant implémenter la syntaxe ci-dessus. La requête de la boucle for est la suivante -

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 ;

La boucle for ci-dessus imprime 1 à 10, c'est-à-dire sous la forme suivante 1,2,3,4,...10. appel stocké Procédure d'utilisation de la commande CALL. La syntaxe est la suivante -

call yourStoredProcedureName();

La requête appelée est la suivante -

mysql> call ForLoop();

output

+-----------------------+
| 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)

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer