Datepart argument of DateAdd

  • Is it possible to allow the datepart argument of the DateAdd function to be passed into a stored procedure?  In my application, the user is allowed to choose whether to add days, months, etc to a date, so I would like that argument to be dynamic.  SQL doesn't allow me to use a varchar there though.  What can I do?

  • There's a couple of different ways to do it, but I'd recommend using CASE statements, honestly.

    SELECT column1, column2,

    CASE

    WHEN @date_part = 'd' THEN DATEADD(d, @some_val, column3)

    WHEN @date_part = 'm' THEN DATEADD(m, @some_val, column3)

    WHEN @date_part = 'y' THEN DATEADD(y, @some_val, column3)

    END AS column3_added

    FROM table

Viewing 2 posts - 1 through 1 (of 1 total)

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