Just discovered a new trick, one that speeds up my SQL. I often use datetime columns and hate the SQL Server format where all dates include the time, which results in date conversion or bizarre arithmetics. Here ’s a nice solution
RETURN CAST( FLOOR( CAST( @d AS INTEGER) ) AS DATETIME )
What does it do? The cast/floor/cast trio pushes the internal datetime to a float, then removes the decimal part and converts it back to a datetime, as the time portion of the datetime datatype in SQL server is stored in the decimal places of a float equivalent type, then converting to an integer removes them and sets the date to midnight.
August 20, 2008 at 9:38 pm |
convert(varchar(20),getdate(),108)
March 6, 2009 at 3:33 am |
The initial cast should be a cast to float:
RETURN CAST( FLOOR( CAST( @d AS FLOAT) ) AS DATETIME )
Otherwise the time fraction will cause a round up to the next full day.