I have a date field with varchar data type and some of the values are for example 20220101000009CS.
I need to show date as (MM/dd/yyyy HH:mm:ss’) and tried the below query but getting the error ‘Conversion failed when converting date and/or time from character string.’
select convert(datetime, 'DATE',20)
from [TABLE1].[dbo].[ABC]
Please advice how do I get around this.
>Solution :
You can use STUFF to inject the needed characters in the right place to get the format yyyyMMdd hh:mm:ss which is also unambiguous in SQL Server:
SELECT V.YourColumn,
CONVERT(datetime2(0),STUFF(STUFF(STUFF(LEFT(V.YourColumn,14),13,0,':'),11,0,':'),9,0,' '))
FROM (VALUES('20220101000009CS'))V(YourColumn);