The problem is in
+ CAST(YEAR(DATEADD(dd, -1, DATEADD(month , n.n + DATEDIFF(month, 0, @Today) -1 , 0))) AS VARCHAR(4))
- see the
-1
... you're looking at the year of the previous month in the sequence - it should be
+ CAST(YEAR(DATEADD(dd, -1, DATEADD(month , n.n + DATEDIFF(month, 0, @Today), 0))) AS VARCHAR(4))
Here is another alternative for generating the same sequence - it will be slightly more performant as there is less formatting going on
DECLARE @Today DATETIME, @nMonths TINYINT
SET @nMonths = 12
SET @Today = DATEADD(month, (-1) * @nMonths, GETDATE())
;WITH q AS
(
SELECT @Today AS datum
UNION ALL
SELECT DATEADD(month, 1, datum)
FROM q WHERE datum + 1 < GETDATE()
)
SELECT SUBSTRING(DATENAME(MONTH, datum), 1, 3) + CAST(YEAR(datum) AS VARCHAR(4))
FROM q
taken from Manas' work at
Generating a Sequence in SQL[
^]