Why does this fail:
DECLARE @DATE VARCHAR(50) = 'dasf'
SELECT CASE WHEN ISDATE(@DATE) = 1 THEN CONVERT(date,@DATE) ELSE @DATE END
Msg 241, Level 16, State 1, Line 2
Conversion failed when converting date
and/or time from character string.
Why is it trying to convert dasf to date when it clearly causes ISDATE(@DATE) = 1 to evaluate to false…
If I do:
SELECT ISDATE(@DATE)
The return value is 0.
CASE returns a single type. In this case, the type is Date, found from your THEN clause. It is implicitly converting the ELSE clause result to Date to match.
You must choose a single type to be returned by CASE. It cannot be used to return sometimes Date and sometimes varchar.
from MSDN:
http://msdn.microsoft.com/en-us/library/ms181765.aspx
and then following that link: http://msdn.microsoft.com/en-us/library/ms190309.aspx
It’s not clear what you want, so it’s hard to offer alternatives (I don’t know if the CASE is part of a larger query or script), but here’s a couple things you can do: