MySQL Function to add a number of working days to a DATETIME

Jason Bristol picture Jason Bristol · Jul 18, 2013 · Viewed 9.4k times · Source

I need a MySQL Function that will allow me to pass a number of working days (Monday - Friday) and a start DATE or DATETIME (doesn't matter for my implementation), and have it return a new DATE or DATETIME that many work days in the future.

Example: SELECT AddWorkDays(10, "2013-09-01") returns "2013-09-16" assuming "2013-09-01" is a Monday.

Similarly: SELECT AddWorkDays(-10, "2013-09-16") returns "2013-09-01"

I found this function for an MSSQL database (I think) that is exactly what I need except its not in MySQL. I tried to manually convert it into MySQL syntax and got about this far:

DROP FUNCTION IF EXISTS AddWorkDays;
DELIMITER $$
CREATE FUNCTION AddWorkDays
(
    WorkingDays INT,
    StartDate DATE
)
RETURNS DATE

BEGIN
    DECLARE Count INT;
    DECLARE i INT;
    DECLARE NewDate DATE;
    SET Count = 0;
    SET i = 0;

    WHILE (i < WorkingDays) DO
        BEGIN
            SET Count = Count + 1;
            SET i = i + 1;
            WHILE DAYOFWEEK(ADDDATE(StartDate, Count)) IN (1,7) DO
                BEGIN
                    SET Count = Count + 1;
                END;
            END WHILE;
        END;
    END WHILE;

    SET NewDate = ADDDATE(StartDate, Count);
    RETURN NewDate;

END;
$$

DELIMITER ;

I end up getting an error:

Error 1415: Not allowed to return a result set from a function

I can't seem to figure out where exactly it is trying to return a result set.

Is there an error in my syntax? Are there any better solutions?

Thanks!

EDIT

It appears MySQL doesn't have a DATEPART or DATEADD function. I see in the documentation that they have ADDDATE and DAYOFWEEK. Updated the code to represent this. I also changed the SELECT statements to SET (Makes sense now why I was getting the original error)

As a result I get a new error when attempting to run a query using the function via CF

[Table (rows 1 columns ADDWORKDAYS(10,"2013-09-01")): [ADDWORKDAYS(10,"2013-09-01"): coldfusion.sql.QueryColumn@7a010] ] is not indexable by ADDWORKDAYS(10

Answer

Giovanni Guarino picture Giovanni Guarino · Jul 18, 2013

This is new function with mysql syntax:

DROP FUNCTION IF EXISTS AddWorkDays;
DELIMITER $$
CREATE FUNCTION AddWorkDays
(
    WorkingDays INT,
    StartDate DATETIME
)
RETURNS DATETIME

BEGIN
    DECLARE Count INT;
    DECLARE i INT;
    DECLARE NewDate DATETIME;
    SET Count = 0;
    SET i = 0;

    WHILE (i < WorkingDays) DO
        BEGIN
            SELECT Count + 1 INTO Count;
            SELECT i + 1 INTO i;
            WHILE DAYOFWEEK(DATE_ADD(StartDate,INTERVAL Count DAY)) IN (1,7) DO
                BEGIN
                    SELECT Count + 1 INTO Count;
                END;
            END WHILE;
        END;
    END WHILE;

    SELECT DATE_ADD(StartDate,INTERVAL Count DAY) INTO NewDate;
    RETURN NewDate;

END;
$$

DELIMITER ;