
- Learn MySQL
- MySQL - Home
- MySQL - Introduction
- MySQL - Installation
- MySQL - Administration
- MySQL - PHP Syntax
- MySQL - Connection
- MySQL - Create Database
- MySQL - Drop Database
- MySQL - Select Database
- MySQL - Data Types
- MySQL - Create Tables
- MySQL - Drop Tables
- MySQL - Insert Query
- MySQL - Select Query
- MySQL - Where Clause
- MySQL - Update Query
- MySQL - Delete Query
- MySQL - Like Clause
- MySQL - Sorting Results
- MySQL - Using Join
- MySQL - NULL Values
- MySQL - Regexps
- MySQL - Transactions
- MySQL - Alter Command
- MySQL - Indexes
- MySQL - Temporary Tables
- MySQL - Clone Tables
- MySQL - Database Info
- MySQL - Using Sequences
- MySQL - Handling Duplicates
- MySQL - SQL Injection
- MySQL - Database Export
- MySQL - Database Import
How MySQL WHILE loop statement can be used in stored procedure?
As we know that MySQL provides us loop statements that allow us to execute a block of SQL code repeatedly based on a condition. WHILE loop statement is one of such kind of loop statements. Its syntax is as follows −
WHILE expression DO statements END WHILE
Actually, the WHILE loop checks the expression at the starting of every iteration. If the expression evaluates to true, MySQL will execute statements between WHILE and END WHILE until the expression evaluates to false. The WHILE loop checks the expression before the statements execute, that is why it is also called the pretest loop.
To demonstrate the use of WHILE loop with stored procedures, the following is an example −
mysql> Delimiter // mysql> CREATE PROCEDURE While_Loop() -> BEGIN -> DECLARE A INT; -> DECLARE XYZ Varchar(50); -> SET A = 1; -> SET XYZ = ''; -> WHILE A <=10 DO -> SET XYZ = CONCAT(XYZ,A,','); -> SET A = A + 1; -> END WHILE; -> SELECT XYZ; -> END // Query OK, 0 rows affected (0.31 sec)
Now, we can see the result below when we invoke this procedure −
mysql> DELIMITER ; mysql> call While_Loop(); +-----------------------+ | XYZ | +-----------------------+ | 1,2,3,4,5,6,7,8,9,10, | +-----------------------+ 1 row in set (0.03 sec)
- Related Articles
- How MySQL REPEAT loop statement can be used in stored procedure?
- How Can MySQL LOOP statement be used in a stored procedure?
- How Can MySQL CASE statement be used in stored procedure?
- How MySQL IF statement can be used in a stored procedure?
- How MySQL IF ELSE statement can be used in a stored procedure?
- How can MySQL IF ELSEIF ELSE statement be used in a stored procedure?
- How can local variables be used in MySQL stored procedure?
- How can user variables be used in MySQL stored procedure?
- How to use FOR LOOP in MySQL Stored Procedure?
- How to loop thrugh a stored procedure in MySQL?
- How can a MySQL stored procedure call another MySQL stored procedure inside it?
- How can we invoke MySQL stored procedure?
- How to call a stored procedure using select statement in MySQL?
- How to implement WHILE LOOP with IF STATEMENT MySQL?
- How can we alter a MySQL stored procedure?

Advertisements