I want to produce a column of dates between a predetermined start and end date and store the result in a CTE to use within my query. The recursive method below does work but using maxrecursion within a CTE doesn't seem to be possible. Is there another way around this?
(1) This works fine:
DECLARE @startnum INT=1
DECLARE @endnum INT=10000
;
WITH gen AS (
SELECT @startnum AS num
UNION ALL
SELECT num+1 FROM gen WHERE num+1<=@endnum
)
SELECT * FROM gen
option (maxrecursion 10000)
(2) This won't work:
DECLARE @StartDate DATE;
DECLARE @EndDate DATE;
SET @StartDate = '20150406';
SET @EndDate = '20190406';
DECLARE @startnum INT=1
DECLARE @endnum INT=10000
;
WITH gen AS (
SELECT @startnum AS num
UNION ALL
SELECT num+1 FROM gen WHERE num+1<=@endnum
)
,
num_list as (
SELECT * FROM gen
option (maxrecursion 10000)
)
,
tab_dates as (
SELECT DATEADD(DAY, nbr - 1, @StartDate) AS Dates
FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY c.num) AS Nbr
FROM num_list c
) nbrs
WHERE nbr - 1 <= DATEDIFF(DAY, @StartDate, @EndDate)
)
SELECT * FROM tab_dates