我们的ERP系统在单独的int列中保存年,月和日。我想将这3个int列合并为一个DateTime,如何在SQL Server中将其转换。
Year | Month | Day
--------------------
2016 | 1 | 23
答案 0 :(得分:10)
您可以使用DATEFROMPARTS
(SQL Server 2012+
):
SELECT DATEFROMPARTS([Year], [Month], [Day]) AS DateTim
FROM table_name
SQL Server 2008
(假设那一年是4位数):
SELECT CAST(CAST([year] AS VARCHAR(4)) + '-' +
CAST([month] AS VARCHAR(2)) + '-' +
CAST([day] AS VARCHAR(2))
AS DATE) AS DateTim
FROM table_name;
的 LiveDemo
强>
正如评论中提出的 Gordon Linoff 一样,YYYYMMDD
用INT
转换为DATE
:
SELECT CAST(CAST([year] * 10000 + [month]*100 + [day] AS VARCHAR(8))
AS DATE) AS DateTim
FROM table_name;
的 LiveDemo2
强>
要解决有关dateformat的 ypercubeᵀᴹ 问题,我们可以使用不受DATEFORMAT
或LANGUAGE
设置影响的ISO-8601
:
YYYY-MM-DDTHH:MM:SS [.mmm]
SELECT CAST(RIGHT('000'+ CAST([year] AS VARCHAR(4)),4) + '-' +
RIGHT('0' + CAST([month] AS VARCHAR(2)),2) + '-' +
RIGHT('0' + CAST([day] AS VARCHAR(2)),2) + 'T00:00:00' AS DATE)
FROM table_name
的 LiveDemo3
强>
处理1000之前的年份应该用零填充。
答案 1 :(得分:1)
我们可以使用SQL的CONVERT函数来获取Datetime值:
SELECT CONVERT(DATETIME, CONVERT(VARCHAR(2), Day) + '/' + CONVERT(VARCHAR(2), Month) + '/' + CONVERT(VARCHAR(4), Year),103) FROM Table_Name