Tuesday 1 July 2008

Get the date portion of a datetime for sql server 2000

Using T-SQL in SQL Server 2000 you sometimes want compare a given datetime value with date by ignoring the time portion of the datetime value.

Here are three ways to strip off the time which gives the following:
2007-06-21 11:23:41.321 => 2007-06-21 00:00:00.000

1) convert to string in format (ISO yymmdd), then cast to datetime
- select on 500000 items takes 1703 ms

SELECT CAST( CONVERT( CHAR(8), GetDate(), 112) AS DATETIME)

2) convert to number of days in float, cut all that is smaller than a day, then cast to datetime
- select on 500000 items takes 228 ms

SELECT CAST( FLOOR( CAST( GETDATE() AS FLOAT ) ) AS DATETIME )

3) get the difference form zero date as number of days, then add this number to zero date.
- select on 500000 items takes 184 ms

SELECT DATEADD(d, 0, DATEDIFF(d, 0, GETDATE()))



Performance tested like this.

SET DATEFORMAT dmy
SET STATISTICS IO ON
SET STATISTICS TIME ON
select myDateTime
from #dummy
where CAST( FLOOR( CAST( myDateTime AS FLOAT ) ) AS DATETIME ) = '02/07/2007'
SET STATISTICS TIME OFF
SET STATISTICS IO OFF