Best approach to remove time part of datetime in SQL Server

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

    Here I made a function to remove some parts of a datetime for SQL Server. Usage:

    • First param is the datetime to be stripped off.
    • Second param is a char:
      • s: rounds to seconds; removes milliseconds
      • m: rounds to minutes; removes seconds and milliseconds
      • h: rounds to hours; removes minutes, seconds and milliseconds.
      • d: rounds to days; removes hours, minutes, seconds and milliseconds.
    • Returns the new datetime

    create function dbo.uf_RoundDateTime(@dt as datetime, @part as char) returns datetime as begin if CHARINDEX( @part, 'smhd',0) = 0 return @dt; return cast( Case @part when 's' then convert(varchar(19), @dt, 126) when 'm' then convert(varchar(17), @dt, 126) + '00' when 'h' then convert(varchar(14), @dt, 126) + '00:00' when 'd' then convert(varchar(14), @dt, 112) end as datetime ) end

提交回复
热议问题