SQL Server Convert from string datetime in ISO format to ANSI

bttbmeg0  于 2023-10-15  发布在  其他
关注(0)|答案(1)|浏览(110)

I have a varchar column that provides datetimes in the following format

yyyymmddhhmmss

In order to store this in a datetime2 column I need to convert it to ANSI format

yyyy-mm-dd hh:mm:ss

There is a convert function I have used for similar columns formatted in UK format e.g. 04/10/2023 11:15:00 can be solved with CONVERT(datetime2(0),COLUMN,103).

The issue is I face an error when attempting this with

SELECT TOP (5) 
       [HistoryID]
      ,[CheckedBy]
      ,[CheckedTime]
      ,CheckedTime2 = SUBSTRING(CheckedTime,1,4) + '-' + SUBSTRING(CheckedTime,5,2) + '-' + SUBSTRING(CheckedTime,7,2) + ' ' + SUBSTRING(CheckedTime,9,2) + ':' + SUBSTRING(CheckedTime,11,2) + ':'  + SUBSTRING(CheckedTime,13,2)
      --,CONVERT(datetime2(0),CheckedTime,112)  
      ,CONVERT(datetime2(0),
      SUBSTRING(CheckedTime,1,4) + '-' + SUBSTRING(CheckedTime,5,2) + '-' + SUBSTRING(CheckedTime,7,2) + ' ' + SUBSTRING(CheckedTime,9,2) + ':' + SUBSTRING(CheckedTime,11,2) + ':'  + SUBSTRING(CheckedTime,13,2)
      ,120) AS [CheckedTime3]
      ,[RevokedBy]
      ,[RevokedTime]
      ,[AnalystRef]
  FROM [staging].[AccuracyChecks]

The above generates the following

HistoryIDCheckedByCheckedTimeCheckedTime2CheckedTime3
63061C5F-0062-02056B951202208250820572022-08-25 08:20:572022-08-25 08:20:57
63061C5F-0062-02056B961202208250820572022-08-25 08:20:572022-08-25 08:20:57
63061CBC-0062-02056B971202208250820532022-08-25 08:20:532022-08-25 08:20:53
63061CBC-0062-02056B981202208250820532022-08-25 08:20:532022-08-25 08:20:53
63061E55-0062-02056B991202208250820262022-08-25 08:20:262022-08-25 08:20:26

As you can see when I use the substring method or convert with the substring method, it generates it correctly.

The commented-out line

CONVERT(datetime2(0),CheckedTime,112)

produces the following error

Conversion failed when converting date and/or time from character string.

The only difference I can see in the docs is the style code 112 does not include TIME data.

What would be the correct way to convert to the required format as using the SUBSTRING method causes a different error related to a filter which I have previously had help resolving through the CONVERT function.

Although I doubt it matters, I have no control over the format I receive the data in.

j2qf4p5b

j2qf4p5b1#

So in answer to my original question, it doesn't appear that there is a way to use CONVERT with it in that format style (yyyymmddhhmmss).

Upon suggestion in the comments, I added a new datetime2 column to the staging table. Using this new column, I altered the SP to update that column using the original SUBSTRING method, only for the filtered records I was working on at that time. I was able to then use the newly created column in the MERGE statement and this avoided the order of operation error seen before.

相关问题