Thursday, July 30, 2020

List all Dates between two dates in SQL Server


This below query to get all dates between the given date range.

DECLARE @StartDateTime DATETIME
DECLARE @EndDateTime DATETIME
 
SET @StartDateTime = '2020-01-01'
SET @EndDateTime = '2020-01-12';
 
WITH DateRange(DateData) AS 
(
    SELECT @StartDateTime as Date
    UNION ALL
    SELECT DATEADD(d,1,DateData)
    FROM DateRange 
    WHERE DateData < @EndDateTime
)
SELECT DateData
FROM DateRange
OPTION (MAXRECURSION 0)
GO

No comments: