Technical Article

BusinessDaysToCalendarDays (For Unusual Business Weeks)

,

SELECT * FROM dbo.BussinesDaysToCalendarDays (3, DATEPART(WEEKDAY,GETDATE()),0,1,1,0,1,1,0)

-- How many calendar days are needed to complete 3 bussines days starting today if the bussiness week is Monday, Tuesday, Thursday and Friday.

SELECT * FROM dbo.BussinesDaysToCalendarDays (4, 3,0,1,0,0,1,1,1)

--How many calendar days are needed to complete 4 bussines days starting Tuesday if the bussiness week is Monday, Thursday, Friday, Saturday

CREATE FUNCTION [dbo].[BussinesDaysToCalendarDays]
(
    @BussinesDays INT,
    @WeekDayToStart INT,
    @Sunday BIT,
    @Monday BIT,
    @Tuesday BIT,
    @Wednesday BIT,
    @Thursday BIT,
    @Friday BIT,
    @Saturday BIT        
)
RETURNS TABLE
AS 
RETURN
(
    WITH Digits(Digit) AS ( SELECT 0 UNION SELECT 1 UNION SELECT 2 UNION 
                            SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION
                            SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION 
                            SELECT 9 ),
     Numbers(Number) AS ( SELECT Centuries.Digit * 100 + Tents.Digit * 10 + Units.digit 
     FROM Digits Units 
     CROSS JOIN Digits Tents 
     CROSS JOIN Digits Centuries 
     ), -- This is just a tally table from 0 to 999
     
     WeekDays([WeekDay],IsBussinesDay) AS ( SELECT 1,@Sunday UNION
                                                SELECT 2,@Monday UNION
                                                SELECT 3,@Tuesday UNION
                                                SELECT 4,@Wednesday UNION
                                                SELECT 5,@Thursday UNION
                                                SELECT 6,@Friday UNION
                                                SELECT 7,@Saturday 
     )
     
     
    SELECT CalendarDays = MAX([CalendarDay]) FROM 
    (
        SELECT TOP (@BussinesDays)
             [CalendarDay] = d.Number + 1 ,
             wd.[WeekDay],
             w.IsBussinesDay 
        FROM Numbers d 
        CROSS APPLY (SELECT [WeekDay] = ((@WeekDayToStart -1 + d.Number ) % 7) + 1 ) wd
        INNER JOIN Weekdays w ON w.WeekDay = wd.WeekDay
        WHERE Number BETWEEN 0 AND 365 AND w.IsBussinesDay = 1
        ORDER BY d.Number 
    ) BussinesDays
)

Rate

2 (1)

You rated this post out of 5. Change rating

Share

Share

Rate

2 (1)

You rated this post out of 5. Change rating