I'm converting varchar data to date in SQL server.
Table having data like below,
So it can have NULL value, proper formatted date and can have like 19900411and 04221995.
So I have tried something like below, but getting error.
SELECT CASE
WHEN ISNULL(CAST(Dob AS VARCHAR), '') = '' THEN NULL
WHEN LEN(CAST(Dob AS VARCHAR)) = '8' THEN CONVERT(
VARCHAR(10),
CONVERT(date, RIGHT(Dob, 4) + LEFT(Dob, 2) + SUBSTRING(Dob, 3, 2)),
103
)
ELSE CONVERT(VARCHAR, CAST(Dob AS CHAR(8)), 103)
END
FROM TableName
WHERE Dob IS NOT NULL
Msg 241, Level 16, State 1, Line 3 Conversion failed when converting date and/or time from character string.
I wanted to get output as date format MM-dd-yyyy
Please help me! Thanks!

04221995- pedram12301123December 30th 1123 or November 23rd 1230? It's crucial to be able to identify every format accurately or you end up with errors as the best case scenario or wrong dates in the worst case. - Zohar Peled