Search code examples
t-sqldatedatediff

Is there a way to perform a DATEADD() with a range of increments in T-SQL?


Looking for a shortcut to getting a column with a range of dates +/- 3 days of a specific date. I haven't found an elegant shortcut. My premise maybe off, I haven't found a way to have a range of values in the increment parameter of DATEADD() but this is the gist of what I am looking to do.

SELECT    
    DATEADD(dd, BETWEEN -3 AND 3, x.myDate)       [Dates]
FROM
    myTable x

I know that this doesn't work but wanted to know if there was an equivalent shortcut to get the desired dates.


Solution

  • To construct a date range you could use a tally table or row-constructor:

    SELECT *,
           DATEADD(dd, s.c, x.myDate)       [Dates]
    FROM myTable x
    CROSS APPLY (VALUES (-3),(-2),(-1),(0),(1),(2),(3)) s(c);
    

    db<>fiddle demo