How to implement WHILE LOOP with IF STATEMENT MySQL?


The following is an example to implement MySQL WHILE LOOP with IF statement. We are using in a stored procedure

The following is the query to create our stored procedure:

mysql> DELIMITER //
mysql> create procedure sp_getDaysDemo()
   -> BEGIN
   -> SELECT MONTH(CURDATE()) INTO @current_month;
   -> SELECT MONTHNAME(CURDATE()) INTO @current_monthname;
   -> SELECT DAY(LAST_DAY(CURDATE())) INTO @total_numberofdays;
   -> SELECT CAST(DATE_FORMAT(NOW() ,'%Y-%m-01') as DATE)INTO @check_weekday;
   -> SELECT DAY(@check_weekday) INTO @check_day;
   -> SET @count_days = 0;
   -> SET @workdays = 0;
   ->
   -> WHILE(@count_days < @total_numberofdays) DO
   -> IF (WEEKDAY(@check_weekday) < 5) THEN
   -> SET @workdays = @workdays+1;
   -> END IF;
   -> SET @count_days = @count_days+1;
   -> SELECT ADDDATE(@check_weekday, INTERVAL 1 DAY) INTO @check_weekday;
   -> END WHILE;  
   ->
   -> select @current_month,@current_monthname,@total_numberofdays,@check_weekday,@check_day;
   -> END
   ->
   -> //
Query OK, 0 rows affected (0.24 sec)
mysql> delimiter ;

Call the stored procedure using CALL command. The syntax is as follows:

CALL yourStoredProcedureName();

Now you can call the stored procedure using the following query:

mysql> call sp_getDaysDemo();

The following is the output:

+----------------+--------------------+---------------------+----------------+------------+
| @current_month | @current_monthname | @total_numberofdays | @check_weekday | @check_day |
+----------------+--------------------+---------------------+----------------+------------+
|              1 | January            | 31                  | 2019-02-01     |          1 |
+----------------+--------------------+---------------------+----------------+------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.02 sec)

Updated on: 30-Jul-2019

342 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements