Поскольку ваша рекурсия года превышает предел рекурсии, ограничения CTE (по умолчанию 100). Вы можете изменить этот лимит, добавив параметр MAXRECURSION.
OPTION (MAXRECURSION 500)
Вы можете добавить эту опцию в конец вашего запроса.
DECLARE @FromYear int, @ToYear int
SELECT @FromYear = 201801,
@ToYear = convert(int,LEFT(CONVERT(char,GETDATE(),112),6))
FROM [Airconnect].[dbo].[CoreNZ]
;WITH CTE AS
(
SELECT @FromYear As TheYear
UNION ALL
SELECT TheYear + 1
FROM CTE
WHERE TheYear < @ToYear
)
SELECT TheYear as [Year],
COUNT
(
CASE WHEN TheYear <= convert(int,LEFT(CONVERT(char,COALESCE([Staff_End_Date], GETDATE()),112),6)) THEN
1
END
) As [No. of Employees.]
FROM CTE
INNER JOIN [dbo].[CoreNZ] ON(TheYear >= convert(int,LEFT(CONVERT(char,Start_Date,112),6)))
GROUP BY TheYear
OPTION (MAXRECURSION 500)
Дополнительная, если вам нужны только год и месяцы, я думаю, что эта версия запроса намного лучше.
DECLARE @FromYear DATE, @ToYear DATE
SELECT @FromYear = '20180101',
@ToYear = CAST(GETDATE() AS DATE)
FROM [Airconnect].[dbo].[CoreNZ]
;WITH CTE AS
(
SELECT @FromYear As TheYear
UNION ALL
SELECT DATEADD(MONTH,1,TheYear)
FROM CTE
WHERE TheYear < @ToYear
)
SELECT TheYear as [Year],
COUNT
(
CASE WHEN TheYear <= COALESCE([Staff_End_Date], GETDATE()) THEN
1
END
) As [No. of Employees.]
FROM CTE
INNER JOIN [dbo].[CoreNZ] ON(TheYear >= Start_Date)
GROUP BY TheYear