在SQL中将数字日期列转换为日期和时间

时间:2013-06-28 16:36:15

标签: sql sql-server date time alter

我目前正在使用SQL Server Management Studio 2008,很久以前就创建了数据库。创建它的人将Date设置为数值,并将GMT Time设置为比实际时间提前4小时,从而在查询中的某处强制执行-4小时功能。我感兴趣的只是使用正确的日期和时间格式转换4小时后当天前4天的数据。

柱: 日期(数字(17,9),非空) Parms(nvarchar(2000),null) ......等等。

   Right now my query is:
   -----
   SELECT ItemId, DATE,
   SUBSTRING(Parms,1,6) +' Was removed from:' AS RemovalPath,
   [OBJECT] AS [MOVE LIST]
   FROM JnlList
   where UserCode = 'Automation' AND ListType = 'M'
   Order by Date DESC, RemovalPath DESC;
   -----
   1 sample row output for my query out of 385 rows is:
   -----
   ItemId: 9393
   Date: 20130627.180846113
   RemovalPath: V77963 Was Removed From:
   MOVE LIST: M-002411
   -----
   REQUIRED OUTPUT:
   ItemId: 9393
   Date: 2013-06-27
   Time: 2:08:46
   RemovalPath: V77963 Was Removed From:
   MOVE LIST: M-002411
   -----

任何人都可以对我的查询进行更改以获得所需的输出吗?非常感谢。

2 个答案:

答案 0 :(得分:5)

试试这个:

;WITH CTE AS
(
    SELECT  CONVERT(DATETIME,LEFT([Date],8)+' '+
                             SUBSTRING([Date],10,2)+':'+
                             SUBSTRING([Date],12,2)+':'+
                             SUBSTRING([Date],14,2)+'.'+
                             RIGHT([Date],3)) [Date],
            ItemId,
            Parms,
            [OBJECT]
    FROM (  SELECT  ItemId,
                    CONVERT(VARCHAR(18),[Date]) [Date],
                    Parms,
                    [OBJECT]
            FROM YourTable
            WEHRE UserCode = 'Automation' AND ListType = 'M') A
)
SELECT  ItemId,
        CONVERT(DATE,[Date]) [Date],
        CONVERT(TIME(0),[Date]) [Time],
        SUBSTRING(Parms,1,6) +' Was removed from:' RemovalPath,
        [OBJECT] [MOVE LIST]
FROM CTE
WHERE [Date] >= CONVERT(DATE,DATEADD(DAY,-4,GETDATE()))

答案 1 :(得分:0)

这样的事情应该有效:

SELECT ItemId,
DATEADD(HH, -4, CONVERT(DATETIME, substring(DATE, 1, 4) + '-' + substring(DATE, 5, 2) + '-' + substring(DATE, 7, 2) + ' ' + substring(DATE, 10, 2) + ':' + substring(DATE, 12, 2) + ':' + substring(DATE, 14, 2) + '.' + substring(DATE, 16, 3))),
SUBSTRING(Parms,1,6) +' Was removed from:' AS RemovalPath,
[OBJECT] AS [MOVE LIST]
FROM JnlList
where UserCode = 'Automation' AND ListType = 'M'
AND DATEADD(HH, -4, CONVERT(DATETIME, substring(DATE, 1, 4) + '-' + substring(DATE, 5, 2) + '-' + substring(DATE, 7, 2) + ' ' + substring(DATE, 10, 2) + ':' + substring(DATE, 12, 2) + ':' + substring(DATE, 14, 2) + '.' + substring(DATE, 16, 3))) > GETDATE() - 4
Order by Date DESC, RemovalPath DESC;