如何将分隔的Year(int),Month(int)和Day(int)列转换为DateTime

时间:2016-03-04 11:27:56

标签: sql sql-server tsql

我们的ERP系统在单独的int列中保存年,月和日。我想将这3个int列合并为一个DateTime,如何在SQL Server中将其转换。

Year | Month | Day
--------------------
2016 | 1     | 23 

2 个答案:

答案 0 :(得分:10)

您可以使用DATEFROMPARTSSQL 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 一样,YYYYMMDDINT转换为DATE

SELECT CAST(CAST([year] * 10000 + [month]*100 + [day] AS VARCHAR(8)) 
           AS DATE) AS DateTim
FROM table_name;

LiveDemo2

附录

要解决有关dateformat的 ypercubeᵀᴹ 问题,我们可以使用不受DATEFORMATLANGUAGE设置影响的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