The problem with your query is the WHERE
condition
WHERE DATEPART(m, DATEADD(m, i+1, @JoiningDate)) <= DATEPART(m, GETDATE())
AND DATEPART(year, DATEADD(m, i+1, @JoiningDate)) <= DATEPART(year, GETDATE())
On the second iteration, Aug - 8
is not less than DATEPART(m, GETDATE()) = 1
I would use the first of the month date and increment by 1 month in the recursive CTE. Then use DATEPART()
on the result
DECLARE @JoiningDate Date
SET @JoiningDate = '2020-07-04 11:21:03.827'
;With MonthYears as
(
SELECT [FirstOfMonth] = DATEADD(MONTH, DATEDIFF(MONTH, 0, @JoiningDate), 0)
UNION ALL
SELECT [FirstOfMonth] = DATEADD(MONTH, 1, [FirstOfMonth])
FROM MonthYears
WHERE [FirstOfMonth] < DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
)
SELECT *,
monthNumber = DATEPART(month, [FirstOfMonth]),
yearNumber = DATEPART(YEAR, [FirstOfMonth])
FROM MonthYears
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…