SQL Server Admin
T-SQL Articles

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'


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



 
  Feedback:

comments

2 Responses to "Find the WeekEnds in this Quarter or Year using SQL Server 2005/2008"
  1. Anonymous said...
    May 26, 2010 2:09 AM

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

  2. Suprotim Agarwal said...
    May 28, 2010 5:19 AM

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

 

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