I need to pass a varchar through a case statement in SQL. The Current data is an integer but I would like to display text.

CASE b.religious_belief
WHEN 01 THEN 'none'     
WHEN 05 THEN 'roman catholic'    
 ELSE 0 
END

I keep getting the error

Conversion failed when converting the varchar value 'none' to data type int.

有帮助吗?

解决方案

All returned values from the CASE clauses should be strings (varchar)

CASE b.religious_belief
    WHEN 01 THEN 'none'     
    WHEN 05 THEN 'roman catholic'    
    ELSE 'Jedi' 
END as MyColumnName

其他提示

CASE b.religious_belief
    WHEN 01 THEN 'none'     
    WHEN 05 THEN 'roman catholic'    
    ELSE '' 
END

The return for the else also needs to be a varchar, so if you're after a "zero" value, then either '' or null would be best.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top