Find off days in a date range using mysql


/ Published in: MySQL
Save to your folder(s)

A function to get off days inside mySQL


Copy this code and paste it in your HTML
  1. DELIMITER $$
  2.  
  3. DROP FUNCTION IF EXISTS `numWeekends`$$
  4.  
  5. CREATE FUNCTION `numWeekends`(first_date DATE, second_date DATE, str_weekends VARCHAR(50)) RETURNS INT(11)
  6. DECLARE start_date DATE;
  7. DECLARE end_date DATE;
  8. DECLARE dayofweekint INT;
  9. IF (first_date < second_date) THEN
  10. SET start_date = first_date;
  11. SET end_date = second_date;
  12. SET start_date = second_date;
  13. SET end_date = first_date;
  14.  
  15. WHILE start_date <= end_date DO
  16. SET dayofweekint = DAYOFWEEK(start_date) - 1;
  17. (dayofweekint < 1)
  18. SET dayofweekint = 7;
  19. (CONCAT('[[:<:]]', str_weekends, '[[:<:]]') REGEXP dayofweekint)
  20. SET diff = diff + 1;
  21. SET start_date = DATE_ADD(start_date,INTERVAL 1 DAY);
  22. END WHILE;
  23.  
  24. RETURN diff;
  25.  
  26. END$$
  27.  
  28. DELIMITER ;

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.