Sql Server: Using CTE to Get All Dates Between Two Specified Dates

Introduction: In this short article I am going to share how to get all dates between the date range we specify in Sql server using CTE (Common table expression).

Get all dates between two specified dates in sql server

Description: While working with sql server database we often need to deal with dates. Few days back I need to get the dates between the date range I specify. There are many ways to get this done but here I have shared how to get this using CTE.

Implementation: Let’s write the query using CTE to select the dates between date range.
DECLARE @StartDate DATE='2017-01-01', @EndDate DATE='2017-01-10';

;WITH DateCTE(DateList) AS
(
            SELECT @StartDate as Date
            UNION ALL
            SELECT DATEADD(d,1,DateList)
            FROM DateCTE WHERE DateList < @EndDate
)
SELECT DateList FROM DateCTE OPTION (MAXRECURSION 0)

Result will be as shown in image above.

 Now over to you:
A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates. 
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..