Click here to Skip to main content
15,912,578 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have date like

Id Date
1 2-10-2015
1 10-10-2016
1 3-10-2017
2 2-10-2015
2 10-10-2016
2 3-10-2017

So i need date that is closest to current date
and not the previous closest date coming closest date
Posted
Updated 20-Dec-15 22:54pm
v2

Try
SQL
select TOP 1 id, [Date]
from Avinash
order by Abs(Datediff(dd, getdate(), [Date])), [Date]

This will find the closest date regardless of whether it is before or after the current date due to the use of Abs
If there are two dates equally close (i.e. x days before current date and x days after) then the query currently returns the earlier date. If you want it to return the future date then order by
SQL
Abs(Datediff(dd, getdate() Asc, [Date])), [Date] Desc
 
Share this answer
 
Try
SQL
SELECT TOP 1 * FROM MyTable 
WHERE [Date] > GETDATE()
ORDER BY DATEDIFF(DAY, [Date], GETDATE()) DESC
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900