Thursday, March 4, 2010

Sql: compare dates without time in sql server

The datetime field in sql server contains both date information and time information e.g.,

expire_date =
2009-12-10 11:50:24.407

This sometimes makes date comparison difficult since when we do

WHERE expire_date = '12/10/2009'

we are actually comparing

2009-12-10 11:50 to 2009-12-10 12:00

To get around this problem, we can use the following syntax

WHERE
CONVERT(datetime, CONVERT(VARCHAR(10), expire_date, 112)) = '12/10/2009'

The trick here is to use two convert functions. The first one converts expire_date into a string of format yyyymmdd (ISO standard, see here), thus stripping out time information. The second convert then converts the string back to datetime format.

No comments: