0

Can any one help how to convert '20200309150920' string to Datetime like 2020-03-09 15:09:20.

0

You can do it within a table as follows:

WITH cte AS
(
  SELECT 
    the_pk,
    CAST
    (
      CONCAT
      (
        SUBSTRING(str, 1, 4),
        '-',
        SUBSTRING(str, 5, 2),
        '-',
        SUBSTRING(str, 7, 2),
        ' ',
        SUBSTRING(str, 9, 2),
        ':',
        SUBSTRING(str, 11, 2),
        ':',
        SUBSTRING(str, 13, 2)
      ) AS DATETIME
    ) AS my_dat
  FROM test t
)
UPDATE test
  SET test.dat = cte.my_dat
FROM 
  test
INNER JOIN
  cte
  ON
    test.the_pk = cte.the_pk;

SQL Server has tricky UPDATE from a SELECT syntax - at least as far as I'm concerned! It's a bit verbose, I know, but I find that indenting helps clarity and maintenance down the road!

0

There may be a better way, but you can do this by concatenating it into the proper form.

DECLARE @TimeString char(20) = '20200309150920'

SELECT CONVERT(datetime2(7), 
    CONCAT(
        SUBSTRING(@TimeString,1,8)
       , ' '
       , SUBSTRING(@TimeString,9,2)
       , ':'
       , SUBSTRING(@TimeString,11,2)
       , ':'
       , SUBSTRING(@TimeString,13,2)
        )
    )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.