Which method provides the best performance when removing the time portion from a datetime field in SQL Server?
a) select DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)
or
b) select cast(convert(char(11), getdate(), 113) as datetime)
The second method does send a few more bytes either way but that might not be as important as the speed of the conversion.
Both also appear to be very fast, but there might be a difference in speed when dealing with hundreds-of-thousands or more rows?
Also, is it possible that there are even better methods to get rid of the time portion of a datetime in SQL?
If possible, for special things like this, I like to use CLR functions.
In this case:
BEWARE!
Method a) and b) does NOT always have the same output!
Output:
2014-01-01 00:00:00.000
Output:
2013-12-31 00:00:00.000
(Tested on MS SQL Server 2005 and 2008 R2)
EDIT: According to Adam's comment, this cannot happen if you read the date value from the table, but it can happen if you provide your date value as a literal (example: as a parameter of a stored procedure called via ADO.NET).
Of-course this is an old thread but to make it complete.
From SQL 2008 you can use DATE datatype so you can simply do:
This method does not use string function.
Date
is basically a real datatype with digits before decimal are fraction of a day.this I guess will be faster than a lot.
I would use:
Thus effectively creating a new field from the date field you already have.