Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Conversion from varchar to Datetime

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading