DROP TABLE IF EXISTS `YourDataBase`.`holidays`;
CREATE TABLE `YourDataBase`.`holidays` (
`DATE` DATE DEFAULT NOT NULL,
`ID` int(10) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=latin1;
DELIMITER $$
DROP FUNCTION IF EXISTS `YourDataBase`.`WORKDAYS`$$
CREATE FUNCTION `YourDataBase`.`WORKDAYS`(first_date DATETIME, second_date DATETIME) RETURNS int(11)
DETERMINISTIC
BEGIN
DECLARE start_date DATE;
DECLARE end_date DATE;
DECLARE diff INT;
DECLARE NumberOfWeeks INT;
DECLARE RemainingDays INT;
DECLARE firstDayOfTheWeek INT;
DECLARE lastDayOfTheWeek INT;
DECLARE WorkingDays INT;
DECLARE holiday INT;
IF (first_date < second_date) THEN
SET start_date = first_date;
SET end_date = second_date;
ELSE
SET start_date = second_date;
SET end_date = first_date;
END IF;
## In the original code one was added at the end of the statement to include both days in interval
SET diff = DATEDIFF(end_date, start_date);
SET NumberOfWeeks=FLOOR(diff/7);
SET RemainingDays=MOD(diff,7);
SET firstDayOfTheWeek=DAYOFWEEK(start_date);
SET lastDayOfTheWeek=DAYOFWEEK(end_date);
IF(firstDayOfTheWeek <= lastDayOfTheWeek) THEN
IF( firstDayOfTheWeek<=6 AND 6 <=lastDayOfTheWeek) THEN SET RemainingDays=RemainingDays-1; END IF;
IF( firstDayOfTheWeek<=7 AND 7 <=lastDayOfTheWeek) THEN SET RemainingDays=RemainingDays-1; END IF;
ELSE
IF( firstDayOfTheWeek=7) THEN SET RemainingDays=RemainingDays-1;
IF (lastDayOfTheWeek=6) THEN SET RemainingDays=RemainingDays-1; END IF;
ELSE SET RemainingDays=RemainingDays-2;
END IF;
END IF;
#Here we count the holidays that had occured during the period where are testing
SELECT COUNT(DATE) INTO @DESC
FROM holidays
WHERE FECHA BETWEEN start_date AND end_date;
SET holiday=@DESC;
SET WorkingDays=NumberOfWeeks*5;
#Here we substract the number of holidays from the working week
IF(RemainingDays>0) THEN RETURN WorkingDays+RemainingDays-holiday;
ELSE RETURN WorkingDays-holiday; END IF;
END;
$$
DELIMITER ;
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (1)
Author
Commented:I didn't intended to cheat buy having two accounts, it was a mistake several years ago an the staf of EE was aware of this.
As for the article Y mut said english is not my primary languaje, Y will do some spell check and post it corrected
Thanks