在循环中使用IF语句MYSQL

时间:2013-06-17 00:41:26

标签: mysql do-while

我想为MySQL创建一个存储例程,用于计算一个月的业务或工作日数(工作日为周一至周五)。

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

  

1064 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以获得正确的语法   靠近'WHILE(@daycount< @totaldays)DO IF(WEEKDAY(@checkweekday)< 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;

1 个答案:

答案 0 :(得分:19)

我发现在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的存储过程或存储例程。现在转到例程选项卡并编辑存储过程以使其成为您想要的。如果您从存储过程开始,我还建议您阅读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 */

注意:如果您使用此功能,请注意此代码不会考虑到全国观察到的假期(或任何假期)。