May 19, 2009

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


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

 
  Feedback:

comments

3 Responses to "Calculate Number of Working Days in SQL Server"
  1. Anonymous said...
    June 29, 2009 at 12:49 PM

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

  2. Karl said...
    May 20, 2010 at 8:02 AM

    Wondefull !

  3. Er. Anand singh said...
    August 11, 2011 at 12:00 AM

    wrong output

 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions