I'm currently writing a TSQL stored proc who need to retrieve a row who is the nearest of my datetime passed as parameter.
Here is the current code :
DECLARE @IdChannel Int
DECLARE @ExactTime Datetime
SET @IdChannel = 1
SET @ExactTime = '2016-01-01 13:31:49.147'
SELECT TOP 1
DER.[DER_DTMODIF]
FROM
[SGPI]..[DER_DECRO_REGIE] DER
INNER JOIN
SGPI..MAI_MACHINE_INPUT MAI ON MAI.MAI_ACTIVE_INPUT = DER.DER_INPUT
AND MAI.MAI_MACHINE_ID = DER.DER_MACHINE_ID
WHERE
(@IdChannel IS NULL OR MAI.MAI_RELATIVE_CHA_ID = @IdChannel)
AND [DER_DTMODIF] /*is the nearest of @ExactTime*/
Here is a snapshot of my data. The request must return 2016/01/01 14:00:17.733 :