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

Change date format for char data type

I have columns with ddmmyyyy in char format.

Date
10112021
11112021
12112021

I want to change that records into yyyymmdd
expected like these

Date
20211110
20211111
20211112

I tried many queries like

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

convert(varchar,DATE, 112) as DATE

but the result is still ddmmyyyy format
and
tried also like this

convert(varchar, cast(DATE as date), 112) as DATE

But the result is

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

any suggestions?

>Solution :

The key problem is that you are storing your date value as a string. You should never do that because it will almost always result in problems further down the line.

Therefore to change the formatting you first have to convert your current string into a valid date and then you use convert to format it as you desire.

SELECT [Date]
    -- First convert to a valid date time - the current format needs to be modified
    , CONVERT(DATE, SUBSTRING([DATE], 1, 2) + '-' + SUBSTRING([DATE], 3, 2) + '-' + SUBSTRING([DATE], 5, 4), 105) [Proper Date Value]
    -- Then convert back to a string in the desired format
    , CONVERT(VARCHAR(8), CONVERT(DATETIME, SUBSTRING([DATE], 1, 2) + '-' + SUBSTRING([DATE], 3, 2) + '-' + SUBSTRING([DATE], 5, 4), 105), 112) [Formatted Date Value]
    -- In fact you can actually just use direct string manipulation in this case
    , SUBSTRING([DATE], 5, 4) + SUBSTRING([DATE], 3, 2) + SUBSTRING([DATE], 1, 2)
FROM (
    VALUES
    ('10112021'),
    ('11112021'),
    ('12112021')
) AS D ([Date]);

Returns:

Date Proper Date Value Formatted Date Value 1 Formatted Date Value 2
10112021 2021-11-10 20211110 20211110
11112021 2021-11-11 20211111 20211111
12112021 2021-11-12 20211112 20211112

Note: You should never use varchar without a length as in many circumstances it defaults to a length of 1 which is then the cause of many hard to find issues.

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