SQL Case语句在条件为true时应用else子句

时间:2018-08-28 14:35:50

标签: sql-server tsql rdbms

当我运行以下sql查询语句时,它不会格式化为numeric(10,0)

但为数字(10,3)。

如果我将cast(Oct as numeric(10,3))替换为null,那么它将起作用。

select case when col='Gallons' 
            then cast(Oct as numeric(10,0))
else cast(Oct as numeric(10,3))
end as Oct
from (select 'Gallons' as col, 225.00 as Oct) a 

为什么会有这种行为?

2 个答案:

答案 0 :(得分:0)

case表达式返回单个类型。它必须在numeric(10, 0)numeric(10, 3)之间决定。后者更为通用,因此将选择它。

如果要控制结果集的外观,则将值转换为字符串:

select (case when col = 'Gallons'
             then cast(cast(Oct as numeric(10, 0)) as varchar(255))
             else cast(cast(Oct as numeric(10, 3)) as varchar(255))
        end) as Oct
from (select 'Gallons' as col, 225.00 as Oct) a 

您也可以使用str()函数。

答案 1 :(得分:0)

要保留两种格式,可以将数字值转换为varchar:

select case when col='Gallons' then cast(cast(Oct as numeric(10,0)) as varchar(max))
else cast(cast(Oct as numeric(10,3)) as varchar(max)) end as Oct
from (select 'Gallons' as col, 225.00 as Oct union all select 'Other' as col, 123.45 as Oct) a 

结果:

enter image description here