Best approach to remove time part of datetime in SQL Server

前端 未结 23 1692
南旧
南旧 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:26

    I think you mean cast(floor(cast(getdate()as float))as datetime)

    real is only 32-bits, and could lose some information

    This is fastest cast(cast(getdate()+x-0.5 as int)as datetime)

    ...though only about 10% faster(about 0.49 microseconds CPU vs. 0.58)

    This was recommended, and takes the same time in my test just now: DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)

    In SQL 2008, the SQL CLR function is about 5 times faster than using a SQL function would be, at 1.35 microseconds versus 6.5 microsections, indicating much lower function-call overhead for a SQL CLR function versus a simple SQL UDF.

    In SQL 2005, the SQL CLR function is 16 times faster, per my testing, versus this slow function:

    create function dateonly (  @dt datetime )
    returns datetime
    as
    begin
    return cast(floor(cast(@dt as float))as int)
    end
    

提交回复
热议问题