将数字转换为长日期

时间:2014-12-18 22:19:31

标签: sql-server formatting type-conversion

SQL数据库中有一列(我正在使用SQL-SMT),数据如下所示:

Date
1021165435
1021215439
1021215441
1021162126
1021162122
1021212135
1021162137
1021212136
1021213136

对于第一个元素,目的是得到类似的东西:21-10-2014 16:54:35但我无法弄清楚如何去做,我已经检查了this post,但是他们使用'%'函数,根据SQL与float和int不兼容。我用这种方式对代码进行了排序:

select [Hora origen ] ,
       nHora= convert(time ,
                 right( '0' + convert(varchar, [Hora origen] / 10000 ) , 2 )
               + ':'
               + right( '0' + (([Hora origen]-([Hora origen] % 100))% 10000)/100 , 2 )
               + ':'
               + right( '0' + convert(varchar, [Hora origen] % 10000 ) , 2 ) 
               )
from Trx_tj$;

但是,它还没有工作

2 个答案:

答案 0 :(得分:0)

这是一种方法:

DECLARE @DatetimeStr VARCHAR(20)
SET @DatetimeStr = '1021165435'
--SET @DatetimeStr = '1021215439'
--SET @DatetimeStr = '1021215441'
--SET @DatetimeStr = '1021162126'
--SET @DatetimeStr = '1021162122'
--SET @DatetimeStr = '1021212135'
--SET @DatetimeStr = '1021162137'
--SET @DatetimeStr = '1021212136'
--SET @DatetimeStr = '1021213136'

SELECT
  DATEADD(SECOND, CAST(SUBSTRING(@DatetimeStr, 9, 2) AS INT),
          DATEADD(MINUTE, CAST(SUBSTRING(@DatetimeStr, 7, 2) AS INT),
                  DATEADD(HOUR, CAST(SUBSTRING(@DatetimeStr, 5, 2) AS INT),
                          DATEADD(DAY,
                                  CAST(SUBSTRING(@DatetimeStr, 3, 2) AS INT),
                                  DATEADD(month,
                                          CAST(LEFT(@DatetimeStr, 2) AS INT) - 1,
                                          CAST('20131231' AS DATETIME))))))

答案 1 :(得分:0)

这是另一种方式:

示例数据

CREATE TABLE temp(
    dateString VARCHAR(20)
)
INSERT INTO temp VALUES
('1021165435'), ('1021215439'), ('1021215441'),
('1021162126'), ('1021162122'), ('1021212135'),
('1021162137'), ('1021212136'), ('1021213136');

WITH CTE AS(
    SELECT
        dateString,
        [Month] = CAST(LEFT(datestring, 2) AS INT) - 1, 
        [Day] = CAST(SUBSTRING(datestring, 3, 2) AS INT)- 1,
        [Hour] = CAST(SUBSTRING(datestring, 5, 2) AS INT),
        [Minute] = CAST(SUBSTRING(datestring, 7, 2) AS INT),
        [Second] = CAST(SUBSTRING(datestring, 9, 2) AS INT)
    FROM temp
)
SELECT
    dateString,
    Formatted = 
        CONVERT(VARCHAR(10), DATEADD(D, [Day], DATEADD(M, [Month], '20140101')), 105) + ' ' +
        CONVERT(VARCHAR(8), DATEADD(SS, [Second], DATEADD(MI, [Minute], DATEADD(HH, [Hour], 0))), 114)
FROM cte