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!
Asked
Active
Viewed 3,360 times
3
-
1@Yuck - Title says `T-SQL` so I'm assuming SQL Server – JNK Aug 10 '11 at 15:59
-
Try this solution as well https://stackoverflow.com/questions/14023145/find-closest-date-in-sql-server – NoWar Jul 19 '17 at 01:28
2 Answers
6
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.

JNK
- 63,321
- 15
- 122
- 138
-2
SELECT *
FROM MyTable
WHERE DateColumn < 'UIDate'
ORDER BY DateColumn DESC
LIMIT 1

CristiC
- 22,068
- 12
- 57
- 89
-
T-SQL syntax is `SELECT TOP (1) * ...` instead of `... LIMIT 1`. – Markus Jarderot Aug 10 '11 at 16:05