试试这个代码:
--declaration of variables
declare @frommonth char(3) = 'jan',@fromyear char(4) = 2011,
@tomonth char(3) = 'APR', @toyear char(4) = 2011
declare @output varchar(max)
declare @f int, @t int
select --setting from and to month as months after 1900-01-01
@f = datediff(month, 0, cast('1' [email protected][email protected] as datetime)),
@t = datediff(month, 0, cast('1' [email protected][email protected] as datetime))
-- recusive loop
;with cte as
(
select @f m
union all
select m + 1 from cte
where m < @t
)
select @output = coalesce(@output +',', '') +stuff(convert(varchar(11),dateadd(mm, m, 0), 109), 4, 6, '''') FROM CTE
select @output
结果:
Jan'11,Feb'11,Mar'11,Apr'11
测试在这里:
http://data.stackexchange.com/stackoverflow/q/114801/declaration-of-variables
为什么特定的递归CTE的要求? –
我们已经创建了一个实现相同的功能。但是为了缓解其他问题,我们正在进行递归CTE。 – suryakiran
这就排除了一些其他可能的方法,比如'XML PATH',它可能(或者可能不会)更高效。 –