In a previous post, I wrote about how to prevent the divide by zero issues in Reporting Services. The problem with the custom code I used was that the code returned the value 0 when one of the numbers is 0 or unknown.

So when the outcoming was NULL, the code returned 0. This result in the value 0 in my reports:

ssrs

I have found a better code on the internet to prevent the divide by zero error in SSRS.

Old code:

Public Function Divide(ByVal first As Double, ByVal second As Double) As Double
If second = 0 OR first = 0
Return 0
Else
Return first / second
End If
End Function

Usage in an expression: Code.Divide(Value A, Value B)

Better Code:
Public Function CalcDivision(ByVal Numerator As Object, _
ByVal Denominator As object, ByVal DivideByZeroDefault As Object) As Object
If Denominator <> 0 Then
Return Numerator/Denominator
Else
Return DivideByZeroDefault
End If
End Function

Usage in an expression: =Code.CalcDivision(Field A, Field B,Nothing)

So it return NULL and not 0! Better solution!

ssrs2

I hope Microsoft will make it easier to fix these kind of thing with less effort. I haven’t tried it in SQL 2014/2016 yet so maybe the already have a solution to prevent Divide By Zero. They should include some cool function by default in SSRS or something like that!

Frequently asked questions

How do I prevent a divide by zero error in SSRS?

Add a custom code function to the report that checks if the denominator is not 0 before it divides. If it is 0, the function returns a default value you pass in. You call it in an expression with Code.CalcDivision.

Why does my SSRS report show 0 instead of an empty value after a division?

The old Divide function returned 0 when one of the numbers was 0 or unknown. So a NULL result also showed as 0 in the report.

How do I return NULL instead of 0 for a division in SSRS?

Use the CalcDivision function and pass Nothing as the third argument: =Code.CalcDivision(Field A, Field B, Nothing). The function then returns NULL when the denominator is 0.

What parameters does the CalcDivision function in SSRS take?

It takes three parameters of type Object: Numerator, Denominator and DivideByZeroDefault. It returns Numerator/Denominator if the denominator is not 0. Otherwise it returns the default value.

What was wrong with the old Divide function in SSRS custom code?

It returned 0 when either number was 0, not only the denominator. A NULL outcome therefore became 0 in the report, which hides missing data.

1 comment

Your email address is not shown. A photo comes from Gravatar, if you have one.

  1. Rogier Pronk

    =IIf(Isnothing(Sum(Fields!Expr2.Value))=true OR Sum(Fields!Expr2.Value)=0 ,"NULL",Sum(Fields!Expr1.Value)/Sum(Fields!Expr2.Value))