Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
579 views
in Technique[技术] by (71.8m points)

reporting services - How to handle IIF or Switch divide by zero giving #ERROR?

I tried using IIF and Switch case, but I am unable to handle N/A case when there would be a divide by zero error. For example:

=switch(
    ReportItems!Textbox54.Value = 0, "N/A",
    ReportItems!Textbox54.Value <> 0, ((ReportItems!Textbox56.Value) / (ReportItems!Textbox54.Value)))

I am getting N/A with out this:

ReportItems!Textbox54.Value <> 0, ((ReportItems!Textbox56.Value) / (ReportItems!Textbox54.Value)

But if add this condition I am getting an error?

I am using SSRS 2008 R2.

Output:

19.47%
13.85%
#Error

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem with the IIF function is that it is a function not a language construct. This means that it evaluates both parameters before passing the parameters to the function. Consequently, if you have a divide by zero error, this will get evaluated and cause an #ERROR condition even when it looks like that code shouldn't be executed due to boolean condition of the IIF statement.

There are two workarounds for this problem:

IIF bypass

Basically make two IIF function calls where you won't get divide by zero errors:

=IIF(ReportItems!Textbox54.Value <> 0, 
    ReportItems!Textbox56.Value / IIF(ReportItems!Textbox54.Value = 0, 1, ReportItems!Textbox54.Value),
    "N/A")

So where ReportItems!Textbox54.Value is zero, divide by 1 instead, throw that result away and use N/A.

Custom Code

Create a safe divide by zero function in custom code where you can use real language constructs.

Public Function SafeDivide(ByVal Numerator As Decimal, ByVal Denominator As Decimal) As Decimal
    If Denominator = 0 Then
       Return 0
    End If
    Return (Numerator / Denominator)
End Function

and then use this in your report for the Value expression instead of IIF or SWITCH:

=Code.SafeDivide(ReportItems!Textbox56.Value, ReportItems!Textbox54.Value)

and use a Format string to display zeroes as "N/A":

#,##0.00;-#,##0.00;N/A

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...