SSRS: Checking for Divide By Zero Using Custom Code

Friday, November 25, 2011
by jsalvo

I encountered a divide-by-zero error while working on an SSRS report and thought the issue could easily be resolved using IIF with code similar to the following:

=IIF(Fields!Denominator.Value = 0, 0, Fields!Numerator.Value/Fields!Denominator.Value)

I soon realized that this does not resolve the issue.  It appears that all parameters  in the IIF function are evaluated regardless if the first parameter evaluates to true or false.  Therefore, the divide-by-zero was still occurring.

After doing some research, I decided that the best option to avoid the divide-by-zero error is to implement custom code.

Note: The following screen shots are from Report Builder 3.0

The first step is to open the Report Properties window.  You can access the report properties by clicking anywhere outside of the report body.

If you still cannot see the Report Properties window, make sure you have the ‘Properties’ option checked in the ‘View’ tab.

image

The Report Properties window is displayed below.  In the Code text box, click the ellipse […].  You may need to click on the Code text box first to see the ellipse button.

image

Next, select ‘Code’ in the left hand menu if it is not already selected.  Paste the code (displayed below screen shot) in the Custom code field.

SNAGHTML9a4f0b7

Function Divide(Numerator as Double, Denominator as Double)
  
If Denominator = 0 Then
  
Return 0
  
Else
  
Return Numerator/Denominator
  
End If
  
End Function

Now that you’ve created the custom code, you can begin to use the code in your report.  The following is an example of how you can use the Divide function in a text box expression:

=Code.Divide(Fields!CurrentYearSales.Value-Fields!PriorYearSales.Value,Fields!PriorYearSales.Value)*100

Comments

comments powered by Disqus