'Convert Varchar date format from yyyy-MM-dd to yyyyMMdd in SQL

Hi I am trying to convert Varchar date format from yyyy-MM-dd to yyyyMMdd in SQL.I tried the below approaches but nothing is working.

Declare @doj VARCHAR(10)
Set @doj='2022-01-01'

Select convert (VARCHAR,@doj,112)
select format(@doj,'yyyyMMdd')

SQL engine is not converting to the required format.If I declared doj variable to date then it is working as expected.How to make it work if the doj is varchar?



Solution 1:[1]

You can just convert to datetime and back again using explicit style numbers:

Declare @doj VARCHAR(10) = '2022-01-01';
SELECT CONVERT(varchar(10), CONVERT(datetime, @doj, 126), 112);

db<>fiddle

Quite why you are storing dates in varchar in the first place is another question...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Charlieface