Best approach to remove time part of datetime in SQL Server

前端 未结 23 1585
南旧
南旧 2020-11-21 22:51

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(         


        
23条回答
  •  清酒与你
    2020-11-21 23:29

    BEWARE!

    Method a) and b) does NOT always have the same output!

    select DATEADD(dd, DATEDIFF(dd, 0, '2013-12-31 23:59:59.999'), 0)
    

    Output: 2014-01-01 00:00:00.000

    select cast(convert(char(11), '2013-12-31 23:59:59.999', 113) as datetime)
    

    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).

提交回复
热议问题