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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s