/* 
 * Arrebol Consultancy copyright.
 * 
 * This code belongs to Arrebol Consultancy
 * its use, redistribution or modification are prohibited 
 * without written authorization from Arrebol Consultancy.
 */
/**
 * Author:  Carlos Janitzio Zavala Lopez <janitzio.zavala@arrebol.com.mx>
 * Created: 10 nov. 2021
 */
DROP FUNCTION IF EXISTS `totalDaysInARangeOfDates`;
-- --------------------------------------------------------
--
-- Estructura para la función `totalDaysInARangeOfDates`
--
DELIMITER //
CREATE FUNCTION `totalDaysInARangeOfDates` (
    startDate DATE,
    endDate DATE,
    excludeSunday BOOL
)
RETURNS INTEGER DETERMINISTIC
BEGIN	
    DECLARE whileDate DATE;
    DECLARE total INTEGER;
    DECLARE totalSundays INTEGER;
    
    SET total = 0;
    SET whileDate = startDate;
    
    WHILE whileDate <= endDate DO		
        SET total = total + 1;
        SET whileDate = DATE_ADD(whileDate, INTERVAL 1 DAY);
    END WHILE;
    
    IF excludeSunday THEN
        SET totalSundays = totalOfSundaysBetweenDates(startDate, endDate);
        SET total = total - totalSundays;
    END IF;
    
RETURN total;
END //
DELIMITER ;