1

I have a query where I am calculating total days between two days including start and end date by the following SQL query. If the end date is not null, then end date is considered as current date.

This query does the job. But I do not want to count Sat and Sundays. Possible public UK Holidays.(I can do this one, if I can get the logic for Saturdays and Sundays)

SELECT  DateDiff(day,DateADD(day,-1,StartDate),ISNULL(EndDate,getDate()))numberOfDays
        FROM <mytable>

How do I count only weekdays between two dates?

Thank you

1

3 Answers 3

4

I would strongly recommend a calendar table for this, especially if you need to take specific holidays into account. Calculating Easter dynamically, for example, is going to be a royal pain.

http://web.archive.org/web/20070611150639/http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-calendar-table.html

If you're going to use T-SQL alone, be careful about using functions that rely on regional/language settings for the output of things like DATENAME ...

2

Take a look at the DATEDIFF MSDN page. At the bottom of the page, there is some user-generated content.
One user posted a function there which does exactly what you want, including holidays (headline: "UDF to return the number of business days, including a check to a bank holidays table").

1

try this

SELECT  DateDiff(day,DateADD(day,-1,StartDate),ISNULL(EndDate,getDate())) - 
( CASE WHEN DATENAME(dw, StartDate) = 'Sunday' OR 
DATENAME(dw,ISNULL(EndDate,getDate())) = 'Sunday' THEN 1 ELSE 0 END)
- ( CASE WHEN DATENAME(dw, StartDate) = 'Saturday' OR 
     DATENAME(dw,ISNULL(EndDate,getDate())) = 'Saturday' THEN 1 ELSE 0 END)
numberOfDays         
FROM <mytable> 
1
  • 1
    How does this handle holidays? Sep 16, 2011 at 13:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.