Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SSRS 2008 - Dealing with division by zero scenarios

Tags:

ssrs-2008

We're running into a problem with one of our reports. In one of our tablixes a textbox has the following expression:

=Iif(Fields!SomeField.Value = 0, 0, Fields!SomeOtherField.Value / Fields!SomeField.Value) 

Which should be pretty self-explanatory. If "SomeField" is zero, set the text box value to zero, else set it to "SomeOtherValue / SomeValue".

What has us stumped is that the report still throws a runtime exception "attempted to divide by zero" even though the above expression should prevent that from happening.

We fiddled a bit with the expression just to make sure that the zero-check is working, and

=Iif(Fields!SomeField.Value = 0, "Yes", "No") 

works beautifully. Cases where the data is in fact zero resulted in the textbox displaying "Yes" and vice versa. So the check works fine.

My gut feel is that the Report rendering engine throws the exception at run-time, because it "looks" as if we are going to divide by zero, but in actual fact, we're not.

Has anyone run into the same issue before? If so, what did you do to get it working?

like image 585
tobias86 Avatar asked Mar 29 '11 11:03

tobias86


People also ask

How to handle divide by zero error in ssrs?

SSRS does not short circuit IIF arguments. Therefore, using a single IIF function to screen for division by zero will have no effect and give an #ERROR value. Instead, a pair of nested IIF statements can be used. The outer IIF controls the value returned in the case of division by zero, 0 in the example above.

How do you stop division by zero?

Arguably the cleanest (mathematically) method to avoid divide by zero errors is to multiply quantities, rather than dividing one by the other.

How do I find divide by zero in SQL?

Method 1: SQL NULLIF Function We place the following logic using NULLIF function for eliminating SQL divide by zero error: Use NULLIF function in the denominator with second argument value zero. If the value of the first argument is also, zero, this function returns a null value.

How do you display zeros as blanks in a SSRS report?

You can use FORMAT function to format numbers, e.g. =Format(Fields! MyField. Value,"0.00").


1 Answers

IIf will always evaluate both results before deciding which one to actually return.

Try

=IIf(Fields!SomeField.Value = 0, 0, Fields!SomeOtherField.Value / IIf(Fields!SomeField.Value = 0, 1, Fields!SomeField.Value)) 

This will use 1 as the divisor if SomeOtherField.Value = 0, which does not generate an error. The parent IIf will return the correct 0 for the overall expression.

like image 67
MartW Avatar answered Oct 10 '22 09:10

MartW