Recursion in CTE

Recursion in CTE

DECLARE @dt_Begin AS DATETIME = '2014-03-01'
DECLARE @dt_End AS DATETIME = '2015-05-31'

DECLARE @tDate AS TABLE
(
cdate DATETIME
)

;WITH CTE AS
(
SELECT @dt_Begin AS cDate
UNION ALL
SELECT DATEADD(M,1,cDate) FROM CTE WHERE cDate < DATEADD(M,-1,@dt_End)
)

INSERT INTO @tDate (cdate)
SELECT cDate FROM CTE ORDER BY cDate
OPTION(MAXRECURSION 0)

SELECT * FROM @tDate

Leave a comment