MS SQL

SQL Server Interview | Get all dates between two dates in SQL Server

We have two input parameters as DateTime input’s, based on the two between dates we need to print date’s

Inputs Dates are below:

We need output like that.

Use the below Query you can get the result.

DECLARE @StartDate DATETIME
DECLARE @Enddate DATETime
SELECT @StartDate = '2021-09-23' , @Enddate = '2021-09-28' 


DECLARE @Days INT = 1
;WITH CTEOutput
AS
(
   SELECT @Days As [Days], @StartDate As startdate, DATEADD(Day,1,@StartDate)  As enddate 
   UNION ALL
   SELECT [Days] + 1, @StartDate, DATEADD(Day,1,enddate) As EndDate FROM CTEOutput
   Where   [Days] < DATEDIFF(DAY,@StartDate,@Enddate)
)
SELECT * FROM CTEOutput

Thanks for your time. Please like and share with friends.

Leave a Reply

Prabhakaran Jayaraman