While Loops In MySQL

Posted on 2007-10-13
Last Modified: 2008-01-09
I am am MS SQL developer and I am busy trying to migrate over to MySQL. I need to populate a table for testing and I would like to do this using a while loop. I noticed that MySQL does support the while conditional statement but for some reason it does not want to work. I noticed that is I wrap it in a stored procedure then it works fine????

Please tell me if I can run a while loop directly or are all conditional statements limited to stored procedures and functions?

Set @i = 0;
while @i < 1000000 do
Insert into payment_instructions (acc_no,acc_type,br_code,br_name,bank_name,instr_val,dt_date)
Values ('4252123521','Current','632005','Witbank','ABSA',138.52,01);
Set @i = @i+1;
end while;
Question by:mwskuzzy
    1 Comment
    LVL 142

    Accepted Solution

    MySQL indeed has the WHILE statement, this however can only be used inside a stored procedure.

    hence, create a procedure:

    create procedure do_job
     declare i int default 0;

    while i < 1000000 do
    Insert into payment_instructions (acc_no,acc_type,br_code,br_name,bank_name,instr_val,dt_date)
    Values ('4252123521','Current','632005','Witbank','ABSA',138.52,01);
    Set i = i+1;
    end while;

    and run that (call do_job).

    Featured Post

    How to improve team productivity

    Quip adds documents, spreadsheets, and tasklists to your Slack experience
    - Elevate ideas to Quip docs
    - Share Quip docs in Slack
    - Get notified of changes to your docs
    - Available on iOS/Android/Desktop/Web
    - Online/Offline

    Join & Write a Comment

    Loading csv or delimited data files to MySQL database is a very common task frequently questioned about and almost every time LOAD DATA INFILE comes to the rescue. Here we will try to understand some of the very common scenarios for loading data …
    I use MySQL for many of my development projects in a Windows environment. To manage my databases (and perform queries) for years I used a tool called MySQL administrator.  This tool has since been replaced by MySQL Workbench. So I decided to m…
    Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
    Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

    754 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now