Sau đây là cú pháp để làm việc với FOR LOOP trong thủ tục lưu trữ 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
// Bây giờ bạn có thể thực hiện cú pháp trên. Truy vấn vòng lặp for như sau -
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 ;
Vòng lặp for ở trên in từ 1 đến 10, tức là ở dạng sau 1,2,3,4, ..... 10. Gọi thủ tục được lưu trữ bằng lệnh CALL. Cú pháp như sau -
call yourStoredProcedureName();
Truy vấn để gọi như sau -
mysql> call ForLoop();
Đầu ra
+-----------------------+ | 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)