SSRS IIF Statement showing #Error when value is non numeric

余生长醉 提交于 2019-12-24 01:14:32

问题


I have a value that will either be a decimal or string. Sample

0.41
0.91
"0 / 2"
0.75

My current expression is =IIF(IsNumeric(Fields!currentRate.Value), Format(CDBL(Fields!currentRate.Value), "P2"), Fields!currentRate.Value)

This properly returns the decimals formatted as a percentage, however the strings are only showing #Error. I've tried messing with various logic in the IIF statement and using a Switch instead. However the decimals always properly show as a percent, while the string only shows #Error.

Is it possible to display both numeric and string values in the same column while maintaining formatting on the numeric value?


回答1:


The error relates to the CDbl function throwing an exception when trying to convert columns that are strings to a number. Yes, I know you're checking if it is numeric first but IIF is not a language construct, it is a function and as a function it evaluates all its parameters before passing them to the function. This means that both the True and False parameters get calculated even though one will be discarded and when it calculates CDbl on a string it throws an error.

Try the Val function. It has the benefit of not throwing errors when it gets passed non-numeric data - it just does the best it can to convert it to a number.

=IIF(IsNumeric(Fields!currentRate.Value), Format(Val(Fields!currentRate.Value), "P2"), Fields!currentRate.Value)



回答2:


IIF() is a function in SQL Server. As such, it returns a value whose type is specified by its arguments. As explained in the documentation:

Returns the data type with the highest precedence from the types in true_value and false_value. For more information, see Data Type Precedence (Transact-SQL).

If one of the two values is a number, then that has precedence. The assumption is that both are numbers. In other words, an expression in SQL only returns one type for all rows.




回答3:


For anyone else who stumbles upon this question. Changing my formatting from using CDBL to VAL allows this to work properly.



来源:https://stackoverflow.com/questions/44621358/ssrs-iif-statement-showing-error-when-value-is-non-numeric

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!