Charlie Rudland Charlie Rudland - 6 months ago 9
SQL Question

SQL dates filter automatic time

I have a datetime column, and we need to run a query on it to look back for two years,

so I need to automate this:

where Appt_DateTime > '20140530' per the current date.

where Appt_DateTime > CURRENT_TIMESTAMP - 2 YEARS


the latter gives an error Msg 102, Level 15, State 1, Line 18
Incorrect syntax near 'YEARS'.

Answer

Try DateAdd(YY,-2,GetDate())

... Where Appt_DateTime >=DateAdd(YY,-2,GetDate())

or

   ... Where Appt_DateTime >=cast(DateAdd(YY,-2,GetDate()) as date)