繁体   English   中英

SQL Server连接日期和时间

[英]SQL server concatenate date and time

我有两列是SQL Server中的“日期时间”类型。 但是,一列包含我需要的有效日期,而另一列仅包含时间(小时,分钟,..)。

如何从第一列中提取日期,从最后一列中提取时间,并将它们连接在一起成为有效的datetime列。

我尝试过的

select 
[Created on],
[Created At],
LEFT([Created On],11),
RIGHT([Created At],8),
LEFT([Created On],11) + RIGHT([Created At],8)
from.. 

但是,输出有意义,但我希望它成为军事格式的有效时间戳类型,如第一列和第二列。 我该怎么做?

在此处输入图片说明

我做了一些谷歌和下面这个解决方案对我有效。

select 
[Created on],
[Created At],
CAST(Convert(date, [Created on]) as datetime) + CAST(Convert(time, [Created At]) as datetime),
LEFT([Created On],11) + RIGHT([Created At],8)
from [VERICAL$Purch_ Inv_ Header] 
where [Posting Date] > '2014-02-01

在此处输入图片说明

尝试使用此表达式:-

select
DATEADD(MILLISECOND,datepart(MILLISECOND,created_at),
DATEADD(SECOND,datepart(SECOND,created_at),
DATEADD(minute,datepart(minute,created_at),
DATEADD(HOUR,datepart(hour,created_at),created_on))))
from ..

实际上,它从created at列中找到时间部分,并添加到created on

使用DATEPART从相应的列中获取相关的日期和时间,并使用DATETIMEFROMPARTS一起归零 (如果在SQL Server 2012上)。

SQLFiddle

应该可以添加它们,+

select 
[Created on],
[Created At],
LEFT([Created On],11),
RIGHT([Created At],8),
[Created On] + [Created At] as whatever

我认为,最干净的方法是利用SQL Server如何实现datetime时间:SQL Server将datetime值实现为一对带符号的32位整数。

  • 高阶单词是日期部分。 它是距1900年1月1日的SQL Server时代的天数偏移量。

  • 低阶字是时间成分。 它是从一天的开始(00:00:00.000)的偏移量(以毫秒为单位)。

掌握了这些知识之后,我们可以看到实现:

select convert(binary(8),convert(datetime,'March 17, 2014'))

回报

0x0000A2F100000000

选择convert(binary(8),convert(datetime,'17:55:23'))

回报

0x0000000001275CE4

因此,要将一个datetime值的日期部分与另一个datetime值的时间部分融合在一起:

convert(datetime,
    substring(convert(binary(8),date_only_column),1,4)
  + substring(convert(binary(8),time_only_column),5,4)
  )

简单!

并格式化为ISO 8601字符串:

convert(varchar(32),
  convert(datetime,
      substring(convert(binary(8),date_only_column),1,4)
    + substring(convert(binary(8),time_only_column),5,4)
    ) ,
    120 -- or 121 if your want milliseconds.
  )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM