如何在MySQL中用IF语句设置WHILE循环?

2022-08-19 00:00:00 mysql do-while

我想为MySQL创建一个存储例程,该例程计算出一个月的营业天数或工作日(工作日从星期一到星期五)。

这是一个语法错误,但我不知道是什么语法错误。它告诉我的是:

1064-您的SQL语法有错误;请查看与您的MySQL服务器版本对应的手册,以了解要使用的正确语法 近‘While(@Day count<;@totalday)do if(Weekday(@check Weekday)<;6) 然后‘在第2行

我的语法错误在以下位置:

WHILE(@daycount < @totaldays) DO
      IF (WEEKDAY(@checkweekday) < 6) THEN

我的代码:

SELECT MONTH(CURDATE()) INTO @curmonth;
SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
SELECT DAY(@checkweekday) INTO @checkday;
SET @daycount = 0;
SET @workdays = 0;

BEGIN
  WHILE(@daycount < @totaldays) DO
      IF (WEEKDAY(@checkweekday) < 6) THEN
        SET @workdays = @workdays+1;
      END IF;
      SET @daycount = @daycount+1;
      SELECT ADDDATE('@checkweekday', INTERVAL 1 DAY) INTO @checkweekday;
  END WHILE;
END;
SELECT @workdays;
    

有人可以协助吗?

更新 我收到以下代码的相同错误,因此可能与以下代码有关:

SET @workdays = 0;
IF (WEEKDAY('2013-06-13') < 6) THEN
  SET @workdays = @workdays+1;
END IF;
SELECT @workdays;

解决方案

我发现在MySQL中不能在存储过程之外使用条件条件。这就是语法错误的原因。只要我把我需要的代码放在

BEGIN
SELECT MONTH(CURDATE()) INTO @curmonth;
SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
SELECT DAY(@checkweekday) INTO @checkday;
SET @daycount = 0;
SET @workdays = 0;

  WHILE(@daycount < @totaldays) DO
    IF (WEEKDAY(@checkweekday) < 5) THEN
      SET @workdays = @workdays+1;
    END IF;
    SET @daycount = @daycount+1;
    SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
  END WHILE;
END

仅供他人使用:

如果您不确定如何在phpmyadmin中创建例程,可以将其放入SQL查询

delimiter ;;
drop procedure if exists test2;;
create procedure test2()
begin
select ‘Hello World’;
end
;;

运行查询。这将创建一个名为Test2的存储过程或存储例程。现在转到Rroutines选项卡并根据需要编辑存储过程。如果您从存储过程开始,我还建议您阅读http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/。

您需要的first_day函数是: How to get first day of every corresponding month in mysql?

显示程序正在运行 只需在End While下方和End上方添加以下行

SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;

然后在SQL查询窗口中使用以下代码。

call test2 /* or whatever you changed the name of the stored procedure to */

注意:如果您使用此代码,请记住此代码不会考虑全国性的节假日(或任何与此相关的节假日)。

相关文章