Sql-server – DD/mm/yyyy in varchar(max) needs to be converted to yyyymmdd format

sql-server-2016

DD/mm/yyyy in varchar(max) needs to be converted to yyyymmdd format
Thought to get the experts opinion.

Below options to convert / cast didn't work:

CONVERT(VARCHAR(19),CONVERT(DATETIME, wfm.date,3),112)
convert(varchar(50), cast(wfm.date as datetime2), 112)
cast(cast(wfm.date as datetime2(15))as datetime)

Getting the error message for convert syntax as

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

For cast syntax getting the error message:

Line 1: Specified scale 15 is invalid.

Best Answer

That's very complex. It's easier than that. Just run,

ALTER TABLE foo
    ALTER COLUMN dt datetime2 NOT NULL;

Where dt is the name of your varchar date field. Now you have it in a date field, and you can simply,

SELECT convert(varchar, mydate, 112)
FROM foo;
Related Question