Calculate Number of Working Days in SQL Server

I recently bumped into this handy query from CMS which shows how to calculate the number of working days in this year till now. The working days are assumed to be Monday to Friday and does not include public holidays, which may be added by you later depending on the country you live in.


DECLARE @StartDate DATETIME


DECLARE @EndDate DATETIME


SET @StartDate = '2009/1/01'


SET @EndDate = GETDATE()


SELECT  


(DATEDIFF(dd, @StartDate, @EndDate) + 1)


-(DATEDIFF(wk, @StartDate, @EndDate) * 2) 


-(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)


-(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)




Assuming the current date is 'May 20, 2009', the number of working days after this query is 100


About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

3 comments:

Anonymous said...

Thanks, it was exactly what i needed, it helped me alot :)

Karl said...

Wondefull !

Anand singh said...

wrong output