SQL Server:日期时间millisec AM / PM强制转换

时间:2019-03-05 15:08:14

标签: sql-server date

将此varchar转换为日期时间的最佳方法是:

'21-DEC-17 11.09.52.020000 AM'

我看过Date and Time Styles页面,但似乎没有一个匹配的页面。谢谢

2 个答案:

答案 0 :(得分:1)

使其可转换为DATETIME

  • 点替换为冒号
  • 0000已删除

SQL

-- results to: 2017-12-21 11:09:52.003
SELECT CAST(REPLACE(REPLACE('21-DEC-17 11.09.52.020000 AM', '.', ':'), '0000', '') AS DATETIME);

如果DATETIME类型不够精确,请考虑使用发布在另一个答案中的DATETIME2方法

答案 1 :(得分:1)

问题实际上是您的2个.所在的地方,您应该拥有:假设,职位没有变化,那么您有多种选择:

WITH N AS
    (SELECT N
     FROM (VALUES (NULL),
                  (NULL),
                  (NULL),
                  (NULL),
                  (NULL),
                  (NULL),
                  (NULL),
                  (NULL),
                  (NULL),
                  (NULL)) N (N) ),
Tally AS
    (SELECT TOP 200
            ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS I
     FROM N N1,
          N N2,
          N N3)
SELECT S.YourDate,
       TRY_CONVERT(datetime2(7), S.YourDate, I) AS ConvertedDate,
       I AS StyleCode
FROM Tally
     CROSS APPLY (VALUES ('21-DEC-17 11.09.52.020000 AM')) V(YourDate)
     CROSS APPLY (VALUES (STUFF(STUFF(V.YourDate, 13, 1, ':'), 16, 1, ':'))) S(YourDate)
WHERE TRY_CONVERT(datetime2(7), S.YourDate, I) IS NOT NULL;

编辑:实际上,如果您更改了两个.,则至少在我的实例和语言上甚至不需要样式代码;但我假设使用DEC之类的值,您正在使用英语衍生词:

SELECT S.YourDate,
       TRY_CONVERT(datetime2(7), S.YourDate) AS ConvertedDate
FROM (VALUES ('21-DEC-17 11.09.52.020000 AM')) V (YourDate)
     CROSS APPLY (VALUES (STUFF(STUFF(V.YourDate, 13, 1, ':'), 16, 1, ':'))) S (YourDate);