我有一个SQL服务器表,其中有一个tinyint列。该列的值将为 0或1或2 。
If it is "0", I have to show "No".
If it is "1", I have to show "Yes".
If it is 2, it needs to show just 2.
以下是我的查询,
select
case when flag=1 then 'Yes'
when flag=0 then 'No'
else flag
end flag
from Employee
当我执行此查询时,我遇到异常,
将varchar值'Yes'转换为数据类型tinyint时转换失败。
答案 0 :(得分:3)
您无法在case
中混合数据类型。将数字输出转换为字符串
select case when flag=1 then 'Yes'
when flag=0 then 'No'
else CAST(flag AS CHAR(1))
end flag
from Employee
答案 1 :(得分:0)
您的Else部分属于TinyInt类型,其他案例语句返回Varchar。这导致了这个问题。您可以使用以下内容解决问题。
(SQL类似于Juergen帖子,但稍作修改)
select case when flag=1 then 'Yes'
when flag=0 then 'No'
else CAST(flag AS Varchar(3))
end flag
from Employee
Tiny Int的大小是0-255,所以我们可以转换为Varchar(3)