Warm tip: This article is reproduced from serverfault.com, please click

Fix datetime string in SQL Server

发布于 2020-11-29 10:24:20

I have a table with 43 000 000 rows. In datetime column data looks 2020.04.22T04:39:29.359 and it's of type VARCHAR.

It looks like an ISO format but there are ., and for ISO I need -. What is the best way to convert the values in these rows to datetime?

One of my variant was subst . to -:

UPDATE table 
SET [Column 3] = REPLACE([Column 3], '.', '-');

but then I need to cut a microseconds from the end.

How to do this cut?

Or maybe you can advice more truish way.

Questioner
navy
Viewed
0
Tim Biegeleisen 2020-11-29 18:41:48

You may use TRY_CONVERT here, after first doing a bit of massaging to bring your raw datetime strings into a format which SQL Server recognizes:

UPDATE yourTable
SET new_dt_col = TRY_CONVERT(
                     datetime,
                     REPLACE(LEFT(dt_col, 19), '.', '-') + '.' + RIGHT(dt_col, 3)
                 );

To be explicit, the replacement logic used above would first convert this:

2020.04.22T04:39:29.359

into this:

2020-04-22T04:39:29.359

You may verify for yourself that the following conversion works correctly:

SELECT TRY_CONVERT(datetime, '2020-04-22T04:39:29.359');