Converting varchar to datetime2 in SQL Server
I'm using SQL Server 2008 R2 and I did an import from a flat file. I couldn't import the datetime
column properly so I specified it temporarily as a varchar(50)
. Now I want to convert it to the datetime2
format. 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:
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
?
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. 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. That's easy enough: LEFT(dateAsStringColumn, 10)
. Now, you need characters 12 through 19 (skipping the dash between date and time), but with the "." replaced by ":". Lastly, tack on characters 20-26 verbatim. Convert that whole thing to a Datetime2 using style 21 (ODBC Canonical with milliseconds).
Try this:
SELECT CONVERT(datetime2, LEFT(myColumn, 10) + " " + REPLACE(SUBSTRING(myColumn, 12, 8), ".", ":") + RIGHT(myColumn, 7), 21) as DateFromString FROM myTable
精彩评论