Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find closest date in SQL Server

I have a table dbo.X with DateTime column Y which may have hundreds of records.

My Stored Procedure has parameter @CurrentDate, I want to find out the date in the column Y in above table dbo.X which is less than and closest to @CurrentDate.

How to find it?

like image 379
MaxRecursion Avatar asked Dec 24 '12 15:12

MaxRecursion


2 Answers

The where clause will match all rows with date less than @CurrentDate and, since they are ordered descendantly, the TOP 1 will be the closest date to the current date.

SELECT TOP 1 * FROM x WHERE x.date < @CurrentDate ORDER BY x.date DESC 
like image 125
ederbf Avatar answered Oct 05 '22 10:10

ederbf


Use DateDiff and order your result by how many days or seconds are between that date and what the Input was

Something like this

    select top 1 rowId, dateCol, datediff(second, @CurrentDate, dateCol) as SecondsBetweenDates     from myTable     where dateCol < @currentDate     order by datediff(second, @CurrentDate, dateCol) 
like image 31
Mikey Mouse Avatar answered Oct 05 '22 10:10

Mikey Mouse