Handle Divide by Zero in SQL Reporting Services

,

Out of the box, Reporting services does not handle divide by zero conditions gracefully.
There are plenty of posting on how to use the IIF() function to accomplish this, with some rather horrific looking code.
In order to simplify the coding process and make the resulting expressions readable by a mere mortal, I wrote the following function that can be included in any report.

Steps:

1. From the menu, choose Report, Report Properties.
2. Click on the Code tab and past the function code into the window.
3. Click on OK

To use the function, you have to reference the code collection in an expression:

=code.CalcRatio( Fields!PYGrossProfit.Value, Fields!PYSales.Value, Nothing)

Or if you want a zero instead of a blank:

=code.CalcRatio( Fields!PYGrossProfit.Value, Fields!PYSales.Value, 0)



' Handle divide by zero gracefully
' simpler than trying to use nested IIF() functions
' Author: Clayton Groom

Public Function CalcRatio(ByVal Numerator As Object, ByVal Denominator As object, ByVal DivZeroDefault As Object) As Object

   If Denominator <> 0 Then
        Return Numerator/Denominator
   Else
        Return DivZeroDefault 
   End If
End Function

Rate

4.5 (14)

Share

Share

Rate

4.5 (14)