Combining (concatenating) date and time into a datetime

后端 未结 12 976
夕颜
夕颜 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 15:30

    Assuming the underlying data types are date/time/datetime types:

    SELECT CONVERT(DATETIME, CONVERT(CHAR(8), CollectionDate, 112) 
      + ' ' + CONVERT(CHAR(8), CollectionTime, 108))
      FROM dbo.whatever;
    

    This will convert CollectionDate and CollectionTime to char sequences, combine them, and then convert them to a datetime.

    The parameters to CONVERT are data_type, expression and the optional style (see syntax documentation).

    The date and time style value 112 converts to an ISO yyyymmdd format. The style value 108 converts to hh:mi:ss format. Evidently both are 8 characters long which is why the data_type is CHAR(8) for both.

    The resulting combined char sequence is in format yyyymmdd hh:mi:ss and then converted to a datetime.

提交回复
热议问题