Creating Rows Between Dates In A Single SQL Statement

  • Hi,

    I am trying to find an easy way to create multiple of just two date in a single sql statement.

    E.G.

    A statement using the parameters

    @StartDate = '2015-01-01'

    @EndDate = '2015-01-05'

    Ends up with rows:

    '2015-01-01'

    '2015-01-02'

    '2015-01-03'

    '2015-01-04'

    '2015-01-05'

    What would be the best way to do this ?

  • declare

    @StartDate date = '2015-01-01',

    @EndDate date = '2015-01-05'

    ;

    SELECT dateadd(DAY, x.rn, @StartDate)

    FROM

    ( SELECT (ROW_NUMBER() OVER(ORDER by object_id))-1 AS rn FROM sys.objects) AS x

    WHERE

    x.rn <= DATEDIFF(DAY,@StartDate,@enddate )

    ;

  • Another perfect situation for a tally table. You can create an in-line table using CROSS JOINs or create a physical tally table and use that. Unfortunately I can't post a cross join because my work server thinks it's some type of "attack" SQL apparently, but the basic SQL with an assumed-to-exist tally CTE/table is:

    SELECT DATEADD(DAY, tally - 1, @StartDate)

    FROM tally

    WHERE tally BETWEEN 1 AND DATEDIFF(DAY, @StartDate, @EndDate) + 1

    SQL DBA,SQL Server MVP(07, 08, 09) A socialist is someone who will give you the shirt off *someone else's* back.

  • Thanks guys

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply