I have a SQL query which used to cause a
Divide By Zero exception
I\'ve wrapped it in a CASE
statement to stop this fr
Percentage = IsNull(ClubTotal/NullIf(AttTotal, 0) * 100, 0)
The solution that I found to handle the divide by zero problem is to create a function that I can call upon to deal the situation, as I often have to perform some sort of ratio/ percentage type analysis. Here's the simple function that I wrote.
Create Function fnRatio(@Numerator decimal(10,2),@Demoninator decimal(10,2))
Returns decimal(10,2)
Begin
Return
Case
When @Demoninator = 0 then 0.00
When @Demoninator Is Null then Null
Else
@Numerator/@Demoninator
End
End
Regards
Jason
A nicer way of doing this is to use NULLIF like this:
Percentage = 100 * ClubTotal / NULLIF(AttTotal, 0)
I'm using NULLIF
bit differently, because in some cases I do have to return some value. Usually I need to return 0 when there is a divide by zero error. In that case I wrap whole expression in ISNULL
. So it would be:
Percentage = ISNULL(100 * ClubTotal / NULLIF(AttTotal, 0), 0)
The inner part is evaluated to NULL
and then ISNULL
replaces it with 0.
In my opinion the CASE statement is exactly the way to go. Rather than calculating something you state the value to return for the case that AttTotal is zero. You could even add another case branch for 0 of 0 being 100%.
Just a side note: I would not return 0 when AttTotal is zero and ClubTotal is greater than zero. NULL might be more appropriate. Or you would create strings (e.g. '10.50%') rather than numbers (e.g. 10.5%), containing "No att. total" in case AttTotal is zero:
PercentageString :=
CASE
WHEN AttTotal = 0 AND ClubTotal = 0 then '100%'
WHEN AttTotal = 0 AND ClubTotal <> 0 THEN 'No att. total'
ELSE to_char(ClubTotal / AttTotal * 100) || '%'
END;