MySQL – How to Write Loop in MySQL

Since, I have written courses on MySQL, I quite often get emails about MySQL courses. Here is the question, which I have received quite often.

“How do I loop queries in MySQL?”

Well, currently MySQL does not allow to write loops with the help of ad-hoc SQL. You have to write stored procedure (routine) for the same.

Here is the example, how we can create a procedure in MySQL which will look over the code. In this example I have used SELECT 1 statement and looped over it. In reality you can put there any code and loop over it. This procedure accepts one parameter which is the number of the count the loop will iterate itself.

delimiter //
CREATE PROCEDURE doiterate(p1 INT)
BEGIN
label1: LOOP
SET p1 = p1 - 1;
IF p1 > 0 THEN
SELECT 1;
ITERATE label1;
END IF;
LEAVE label1;
END LOOP label1;
END//
delimiter ;
CALL doiterate(100);

You can also use WHILE to loop as well, we will see that in future blog posts.

Reference: Pinal Dave (http://blog.sqlauthority.com)

About these ads

6 thoughts on “MySQL – How to Write Loop in MySQL

  1. Broke when I pasted your code. Got:
    ERROR 1547 (HV000): column count of mysql.proc is wrong. Expected 20, found 16. The table is probably corrupt. [Ver 14.14 Distrib 5.1.61, for debian-linux-gnu (x86-64) using deadline 6.1.

    Like

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 )

Google+ photo

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

Connecting to %s