Best approach to remove time part of datetime in S

2018-12-31 02: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()), 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?

23条回答
君临天下
2楼-- · 2018-12-31 03:20

select CONVERT(char(10), GetDate(),126)

查看更多
梦醉为红颜
3楼-- · 2018-12-31 03:20

I really like:

[date] = CONVERT(VARCHAR(10), GETDATE(), 120)

The 120 format code will coerce the date into the ISO 8601 standard:

'YYYY-MM-DD' or '2017-01-09'

Super easy to use in dplyr (R) and pandas (Python)!

查看更多
君临天下
4楼-- · 2018-12-31 03:21

How about select cast(cast my_datetime_field as date) as datetime)? This results in the same date, with the time set to 00:00, but avoids any conversion to text and also avoids any explicit numeric rounding.

查看更多
与风俱净
5楼-- · 2018-12-31 03:22

For me the code below is always a winner:

SELECT CONVERT(DATETIME, FLOOR(CONVERT(FLOAT,GETDATE())));
查看更多
骚的不知所云
6楼-- · 2018-12-31 03:22

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

查看更多
美炸的是我
7楼-- · 2018-12-31 03:24

In SQL Server 2008, you can use:

CONVERT(DATE, getdate(), 101)
查看更多
登录 后发表回答