Search code examples
sql-serversql-server-2005t-sql

SQL to return list of years since a specific year


I need a list of years as a recordset starting with 2004 to current year (in desc order), without writing a stored procedure. Is this possible? (SQL Server 2005). So it should return:

2009
2008
2007
2006
2005
2004


Solution

  • This gets all years from 2004 to the present, using a recursive CTE:

    with yearlist as 
    (
        select 2004 as year
        union all
        select yl.year + 1 as year
        from yearlist yl
        where yl.year + 1 <= YEAR(GetDate())
    )
    
    select year from yearlist order by year desc;