June 06, 2009

Find the WeekEnds in this Quarter or Year using SQL Server 2005/2008

Recently I had to pull out the number of weekends in this quarter and list them for a report. Here’s how I did it

DECLARE @date1 datetime
DECLARE
@date2 datetime
SELECT
@date1 = DATEADD(qq,DATEDIFF(qq,0,GETDATE()),0)
SELECT @date2= DATEADD(qq,DATEDIFF(qq,-1,GETDATE()),-1)
;WITH CTE (dt)
AS
(
SELECT @date1
UNION ALL
SELECT DATEADD
(d,1,dt) FROM CTE
WHERE dt < @date2
)
SELECT dt from CTE
WHERE DATENAME(dw,dt) In ('Saturday', 'Sunday')



OUTPUT



image



If you want to list all the weekends in a year, just replace the @date1 and @date2 variables with the appropriate dates as shown here:



SELECT @date1 = '1/1/2009'
SELECT @date2= '12/31/2009'


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

2 comments:

Anonymous said...

Is there a way to rewrite this query by finding the first and last day of the year programmatically, rather than hard coding it?

Suprotim Agarwal said...

I have posted an answer to your question over here http://www.sqlservercurry.com/2010/05/list-all-weekends-of-current-year-using.html