简体   繁体   English

在 SQL 服务器中将 varchar 转换为 datetime2

[英]Converting varchar to datetime2 in SQL Server

I'm using SQL Server 2008 R2 and I did an import from a flat file.我正在使用 SQL Server 2008 R2 并从平面文件导入。 I couldn't import the datetime column properly so I specified it temporarily as a varchar(50) .我无法正确导入datetime列,因此我将其临时指定为varchar(50) Now I want to convert it to the datetime2 format.现在我想将其转换为datetime2格式。 However when doing so I get the error -然而,当我这样做时,我得到了错误 -

Conversion failed when converting date and/or time from character string.从字符串转换日期和/或时间时转换失败。

The data that is currently in my varchar(50) column looks like this:当前在我的varchar(50)列中的数据如下所示:

2008-04-02-16.43.32.179530
2009-01-12-20.15.41.936632
2009-02-18-16.54.49.071662

What's the best way to convert it to datetime2 ?将其转换为datetime2的最佳方法是什么?

Not pretty不漂亮

;WITH T(YourCol) As
(
SELECT '2008-04-02-16.43.32.179530' union all
SELECT '2009-01-12-20.15.41.936632' union all
SELECT '2009-02-18-16.54.49.071662'
)
SELECT CAST(
            STUFF(REPLACE(
                          STUFF(YourCol,11,1,'T')
                  ,'.',':')
            ,20,1,'.')
        AS DATETIME2)
FROM T

Unfortunately, that's not a recognized timestamp format.不幸的是,这不是公认的时间戳格式。 It's close to ODBC Canonical format, but not quite.它接近 ODBC 规范格式,但不完全。 You'll have to do some string manipulation.你必须做一些字符串操作。

If you take the first 10 characters, that's the date in ODBC Canonical (yyyy-mm-dd) format, no changes needed.如果您取前 10 个字符,那就是 ODBC 规范 (yyyy-mm-dd) 格式的日期,无需更改。 That's easy enough: LEFT(dateAsStringColumn, 10) .这很简单: LEFT(dateAsStringColumn, 10) Now, you need characters 12 through 19 (skipping the dash between date and time), but with the "."现在,您需要字符 12 到 19(跳过日期和时间之间的破折号),但需要使用“.”。 replaced by ":".取而代之 ”:”。 Lastly, tack on characters 20-26 verbatim.最后,逐字添加字符 20-26。 Convert that whole thing to a Datetime2 using style 21 (ODBC Canonical with milliseconds).使用样式 21(ODBC 规范,毫秒)将整个事情转换为 Datetime2。

Try this:尝试这个:

SELECT CONVERT(datetime2, LEFT(myColumn, 10) + " " + REPLACE(SUBSTRING(myColumn, 12, 8), ".", ":") + RIGHT(myColumn, 7), 21) as DateFromString FROM myTable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM