0

I have a stored-procedure and I want to add date column to the tables. Then I wonder how do I get MS-SQL to generate multiple rows on the fly using CTE. Say I have this..

(GETDATE() - 548)  --(365 days --> 12 months, 548 days --> 18 months...

How do you guys whip up a query that would create 548 rows and have the date column as row

#1 - '12/17/2012'
#2 - '12/16/2012'
#3 - '12/15/2012'

etc. all the way to row #548? All of that into a CTE?

Thanks...

4

1 回答 1

3

Unless I am missing something, it sounds like you want the following:

;with dates(value) as
(
    select DATEADD(d, -548, cast(getdate() as DATE))
    union all
    select DATEADD(D, 1, value)
    from dates
    where DATEADD(D, 1, value) <= cast(getdate() as DATE)
)
select *
from dates
order by value desc
OPTION (MAXRECURSION 1000)

See SQL Fiddle with Demo

于 2012-12-17T18:34:35.790 回答