如何在 MySQL 中使用 if 语句实现 while 循环?


以下是一个使用 if 语句实现 MySQL while 循环的示例。我们将其用于存储过程中

以下是要创建存储过程的查询

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 命令调用存储过程。语法如下

CALL yourStoredProcedureName();

现在,你可以使用以下查询调用存储过程

mysql> call sp_getDaysDemo();

以下为输出结果

+----------------+--------------------+---------------------+----------------+------------+
| @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)

更新于: 30-Jul-2019

440 次浏览

开启你的 职业生涯

通过完成课程并获得认证

开始学习
广告