Number of Weekdays Between Two Dates
If we want to calculate the number of weekdays between two dates in SQL Server we do not have an in-built function doing that and we have to create our own. There are a number of approaches to doing that and I will describe a few.
1. Using a Date table
If we have a table containing dates, we could add a column to it, which shows if a date is a Weekday (1) or a Weekend (0). Then we could simply sum the values in our query. This is an easy approach, but would not be the most optimal one, as you will see later.
2. Building a function
We can build a function which takes the start and end dates as parameters and then returns the number of weekdays between the two. One way of building that would be to cycle through all the dates between the start and the end, and determine if each of those is a weekday, incrementing a variable if it is. However, this would require looping many times for possibly many dates, which can be slow.
3. SQL Expression
And lastly, if we want a fast performing solution, we can write an expression which will do the work in one go without looping through dates and without accessing the database tables. There are a few solutions online, but I could not find a robust one, so I wrote one myself. It seems to be doing fine, so there it goes:
SET DATEFIRST 1 --start of the week on Monday DECLARE @startDate datetime, @endDate datetime SET @startDate = '2010-08-02' --testing start date SET @endDate = '2010-08-08' -- testing end date SELECT CASE WHEN @startDate > @endDate THEN 0 ELSE ((DATEDIFF(dd, @startDate, @endDate)+1) - DATEDIFF(WW, DATEADD(dd, -@@DATEFIRST, @startDate), DATEADD(dd, -@@DATEFIRST, @endDate))*2 )- CASE WHEN DATEPART(weekday, @endDate) = 6 THEN 1 WHEN DATEPART(weekday, @endDate) = 7 THEN 2 ELSE 0 END + CASE WHEN DATEPART(weekday, @startDate) = 7 THEN 1 ELSE 0 END END
The algorithm does the following:
1. If the start date is after or equal to the end date, return 0
2. Otherwise, get the difference in days between the start and end dates, including both (the +1 bit)
3. Calculate the weeks difference between start and end dates and multiply this by 2, as this is the number of weekend days
4. Subtract the result from 3 from the result from 2
5. If the end date is Saturday, take away one day -> compensates for one extra weekend day
6. If the end date is Sunday, take away two days -> compensates for two extra weekend days
7. If the start date is Sunday, add one day -> add one day, because the week difference is too large
A few interesting findings:
1. DATEDIFF(ww, @startDate, @endDate) does not yield correct results, because it does not take into account the DATEFIRST parameter. Because of that we are adjusting the start and end dates by moving them back.
2. DATEFIRST needs to be set properly (in our case to 1 for start of the week on Monday), unless we are always relying on the default value
Please let me know if you find any issues with the above function.

