While Loop in MySQL Stored Procedure

This is merely to show newcomers how to create a while loop within a stored procedure. Because the while loop requires BEGIN and END statements, it is feasible to put the loop statement inside the stored procedure.

Here’s an illustration.

CREATE TABLE someTable(
Id int,
Col1 int,
Col2 int
);

CREATE PROCEDURE uspInsertRecords()
BEGIN
DECLARE minValueVariable INT DEFAULT 1;
WHILE minValueVariable <= 10 DO
INSERT INTO someTable(Id, Col1, Col2) VALUES (minValueVariable , minValueVariable+1, minValueVariable+10);
SET minValueVariable = minValueVariable + 1;
END WHILE;
END

CALL uspInsertRecords();

select * from someTable;

MySQL_While_Loop

Hope you find this article helpful.

Leave a Reply