-2

SQL Server 2019 is receiving data from upstream PostgreSQL.

The four date columns are defined as datatype Varchar(50) and hold datetime values like this:

2021-12-09 09:16:09+00
2021-12-15T02:40:39+01:00
2021-12-15 1:27:56
2021-12-15 0:45:00

How can I convert this from varchar to proper datetime datatype and insert to another table in SQL Server 2019?

Dale K
  • 25,246
  • 15
  • 42
  • 71
Aryan
  • 57
  • 5

1 Answers1

1

You could try using the base string functions along with TRY_CONVERT() here:

SELECT dt,
       TRY_CONVERT(datetime, SUBSTRING(dt, 1, 10) + ' ' + SUBSTRING(dt, 12, 8)) AS dt_out
FROM yourTable;

Here is a working demo.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360