First Sunday of Every Month in SQL Server

I have often seen questions about finding the First Sunday or Monday of every month in SQL Server. Here’s a query that lists the first Sunday of every month in a given duration

Note: You can also check List all the Weekends of the Current Year using SQL Server and First weekday of a month in SQL Server

DECLARE @dow int,
@StartDate DATETIME,
@EndDate DATETIME
SELECT @dow = 1, -- Sunday
@StartDate = '01 Jan 2010',
@EndDate = '31 Dec 2011'

-- Populate CTE with the 1st date of every month
;WITH CTE(mth) AS (
SELECT @StartDate mth UNION ALL
SELECT DATEADD(month,1,mth) FROM CTE
WHERE DATEADD(month,1,mth) <= @EndDate
)

-- SQLServerCurry.com Query to List First Sunday of all Months
SELECT DATEADD(DAY, @dow +
CASE WHEN DATEPART(dw,mth) > @dow THEN 7
ELSE 0
END
- DATEPART(dw, mth), mth) as 'First Sunday'
FROM CTE

OUTPUT

image

Update: Here's a better query SQL Server: First and Last Sunday of Each Month


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

No comments: