試試這個代碼:
--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',它可能(或者可能不會)更高效。 –