In the table MonthCalender, I have added two date ranges and I am trying to insert monthly start and month end dates within the range.
MonthName | MonthStart | MonthEnd |
---|---|---|
Previous Months | 2010-01-01 00:00:00.000 | 2023-06-01 08:21:30.813 |
UpdateValue | 2023-06-01 08:21:30.817 | 2030-01-01 00:00:00.000 |
I want to insert month start and month end dates like this.
MonthName | MonthStart | MonthEnd |
---|---|---|
Previous Months | 2010-01-01 00:00:00.000 | 2010-02-01 00:00:00.000 |
Previous Months | 2010-02-01 00:00:00.000 | 2010-03-01 00:00:00.000 |
Previous Months | 2010-03-01 00:00:00.000 | 2010-04-01 00:00:00.000 |
Previous Months | 2010-04-01 00:00:00.000 | 2010-05-01 00:00:00.000 |
Previous Months | 2010-05-01 00:00:00.000 | 2010-06-01 00:00:00.000 |
Previous Months | 2010-06-01 00:00:00.000 | 2010-07-01 00:00:00.000 |
... till 2023-06-01 00:00:00.000
The Code is using maxrecursion but that is not supported in synapse. How do I use a loop to insert data within the range?
;WITH cSequence AS (
SELECT 'Previous Months' as MonthName,
Cast('2010-01-01 00:00:00.000' as datetime) AS StartRange,
Cast(DATEADD(m, 1, '2010-01-01 00:00:00.000') as datetime) AS EndRange
UNION ALL
SELECT CASE WHEN EndRange >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) THEN 'UpdateValue' ELSE 'Previous Months' END as MonthName,
EndRange,
DATEADD(m, 1, EndRange)
FROM cSequence
WHERE DATEADD(m, 1, EndRange) < '2030-01-01 00:00:00.000' )
insert into #MonthCalendar
SELECT * FROM cSequence
OPTION (MAXRECURSION 0);