sql-servert-sqldate

T-SQL How to select the nearest earlier date


I have a date that I am grabbing from my UI (mm/dd/year AND hh:mi) and I need to find the nearest date (one record) BEFORE the date in my UI. I was researching, and it seems like DATEDIFF would be the best way to go about this? Or is there a better way to go about this? I'm a little unsure about the syntax. Thank you!


Solution

  • SELECT MAX(DateField)
    FROM Table
    WHERE Datefield < DateFromUI
    

    This will get you the "newest" date that is older than the one passed in the WHERE clause. It should also be compatible with any RDBMS.