将包含日期和时间信息的2列加入datetime

时间:2013-05-08 08:19:46

标签: sql sql-server-2008-r2

我有2列包含

DATE (Varchar),Time (Varchar)
=============================
20121231, 172109
-----------------
20130502, 163107
-----------------
20130502, 163148
------------------
20130502, 163206
------------------
20130502, 163207
-------------------

我想要合并为1个日期时间列 预期结果应该是。

2012-12-31 17:21:09
------------------
2013-05-02 16:31:07
------------------
2013-05-02 16:31:48
------------------
2013-05-02 16:32:06
------------------
2013-05-02 16:32:07
------------------

任何人都可以共享查询。?

4 个答案:

答案 0 :(得分:0)

尝试一下,

这将输出数据类型为DATETIME

的值
CONVERT(DATETIME,STUFF(STUFF([date],5,0,'-'), 8,0, '-') + ' ' + STUFF(STUFF([time],3,0,':'),6,0,':'))

这将输出STRING

STUFF(STUFF([date],5,0,'-'), 8,0, '-') + ' ' + STUFF(STUFF([time],3,0,':'),6,0,':')

后续问题,为什么首先将日期/时间保存为不同列中的varchar?

答案 1 :(得分:0)

select SUBSTRING ( date ,0 , 5 )+
              '-'+
              SUBSTRING ( date ,5 , 2 )+
              '-'+
              SUBSTRING ( date ,7 , 2 )+
              ' '+
              SUBSTRING ( time ,0 , 3 )+
              ':'+
              SUBSTRING ( time ,3 , 2 )+
              ':'+
              SUBSTRING ( time ,5 , 2 )
               as datetime
              from datetime;

SQLFIDDLE

答案 2 :(得分:0)

SQLFiddle demo

select convert(datetime,LEFT([DATE],4)
                        +'-'+
                        SUBSTRING([DATE],5,2)+
                        +'-'+
                        RIGHT([DATE],2)+
                        ' '+
                        LEFT([TIME],2)
                        +':'+
                        SUBSTRING([TIME],3,2)+
                        +':'+
                        RIGHT([TIME],2)
                        ,120)
from t

答案 3 :(得分:0)

请检查

SELECT  REPLACE(CONVERT(VARCHAR(30),
    CONVERT(DATETIME,TM.DateValue),120 ),' 00:00:00',' ')
    +STUFF(STUFF(TM.TimeValue, 3,0,':'),6,0,':')
    FROM TableName TM