您的转换应该是then
,而不是围绕整个case
表达之后。
select
...
, HourlyRate = case when table2.rates in ('2','4')
then convert(varchar(32),convert(decimal(18,4),table1.hourlyrate))
else table1.hourlyrate
end
)
from ...
在SQL Server 2012+,你可以使用try_convert()
而不是convert()
返回而不是错误null
值如果转换失败。
select
...
, HourlyRate = case when table2.rates in ('2','4')
then convert(varchar(32),try_convert(decimal(18,4),table1.hourlyrate))
else table1.hourlyrate
end
)
from ...
rextester演示:http://rextester.com/KYXEV38143
回报:
+-------+------------+------------+
| rates | hourlyrate | HourlyRate |
+-------+------------+------------+
| 1 | 1.23456789 | 1.23456789 |
| 2 | 1.23456789 | 1.2346 |
| 2 | | NULL |
| 3 | 1.23456789 | 1.23456789 |
| 4 | 1.23456789 | 1.2346 |
| 4 | 1 | 1.0000 |
| 4 | N/A | NULL |
+-------+------------+------------+
程序代码(如存储过程)是**高度特定供应商的** - 所以请添加标签到指定是使用了'mysql','postgresql','SQL服务器','oracle'或'db2' - 或者其他的东西。 –
如果rates = 2会怎么样?它只需要2个小数位 – jophab
'THEN table1.hourlyrate ELSE table1.hourlyrate END'部分没有任何意义。 –