[英]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上)。
應該可以添加它們,+
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.