日期:2014-05-18  浏览次数:20509 次

T_sql获取某个时间跨度中的所有年份
比如时间跨度为2002-2012

查询结果为
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012

------解决方案--------------------
SQL code
--sql 2005
declare @startDate datetime
declare @endDate datetime

SELECT @startDate = '2002-01-01' ,@endDate = '2012-01-01'
;WITH tb AS (
SELECT @startDate AS 'date'
UNION ALL
SELECT DATEADD(yy,1,date) FROM tb WHERE datepart(yy,DATE)<datepart(yy,@endDate)
)
SELECT datepart(yy,tb.date) from tb

/*

-----------
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012

(11 行受影响)
*/