Combining (concatenating) date and time into a datetime

后端 未结 12 953
夕颜
夕颜 2020-12-08 15:06

Using SQL Server 2008, this query works great:

select CAST(CollectionDate as DATE), CAST(CollectionTime as TIME)
from field

Gives me two co

12条回答
  •  天命终不由人
    2020-12-08 15:09

    Solution (1): datetime arithmetic

    Given @myDate, which can be anything that can be cast as a DATE, and @myTime, which can be anything that can be cast as a TIME, starting SQL Server 2014+ this works fine and does not involve string manipulation:

    CAST(CAST(@myDate as DATE) AS DATETIME) + CAST(CAST(@myTime as TIME) as DATETIME)
    

    You can verify with:

    SELECT  GETDATE(), 
            CAST(CAST(GETDATE() as DATE) AS DATETIME) + CAST(CAST(GETDATE() as TIME) as DATETIME)
    

    Solution (2): string manipulation

    SELECT  GETDATE(), 
            CONVERT(DATETIME, CONVERT(CHAR(8), GETDATE(), 112) + ' ' + CONVERT(CHAR(8), GETDATE(), 108))
    

    However, solution (1) is not only 2-3x faster than solution (2), it also preserves the microsecond part.

    See SQL Fiddle for the solution (1) using date arithmetic vs solution (2) involving string manipulation

提交回复
热议问题