I am trying to use CASE to group table contents that include characters and NULL and Blank entries using the following:
SELECT COUNT(*) AS Clients,
CASE WHEN t.Diagnosedin = 'Unknown' OR t.Diagnosedin ='' THEN 'Unknown'
ELSE CASE WHEN CAST((CAST(DATENAME(Year,GETDATE()) AS INT)- t.Diagnosedin)AS varchar(5)) =1 THEN 1
ELSE CASE WHEN CAST((CAST(DATENAME(Year,GETDATE()) AS INT)- t.Diagnosedin)AS varchar(5)) <=2 THEN 2
ELSE CASE WHEN CAST((CAST(DATENAME(Year,GETDATE()) AS INT)- t.Diagnosedin)AS varchar(5)) <=5 THEN 5
ELSE CASE WHEN CAST((CAST(DATENAME(Year,GETDATE()) AS INT)- t.Diagnosedin)AS varchar(5)) <=10 THEN 10
ELSE CASE WHEN CAST((CAST(DATENAME(Year,GETDATE()) AS INT)- t.Diagnosedin)AS varchar(5))>=10 THEN '+10 '
END
END
END
END
END
END AS Years
I get the following error: Conversion failed when converting the varchar value 'Unknown' to data type int., I am using MS SQL 2008.
Thanks in advance.
What’s happening is that you’re mixing literals of different datatypes in the column
Years. (i.e. int5and varcharUnknownwill be in the same resultset). You need to code those literal values as the same datatype.Try this:
STR()function, and used theLRTIM()to ensure that the leading spaces aren’t kept.CASE