I am trying to prevent #error being displayed in a report I am creating
This happens when I divide 2 numbers and one of them is zero
So I tried using an if/switch statement to check if either of the 2 number are 0 before doing the divide :
=IIf(Fields!Field1.Value = 0
or Fields!Field2.Value = 0
or Not(IsNumeric(Fields!Field1.Value))
or Not(IsNumeric(Fields!Field2.Value)),
0,
(Fields!Field1.Value/Fields!Field2.Value)*100
)
=Switch(
Fields!Field1.Value = 0 or Fields!Fields.Value = 0, 0,
IsNumeric(Fields!Field1.Value) or IsNumeric(Fields!Fields.Value), (Fields!Field1.Value/Fields!Fields.Value)*100
)
Both of these still throw the error. It seems that the else condition is still evaluated even if the if statement is true
If I change the code to just print X or Y for the if and else, then it works – so there isn’t an error in the if statement
This sems ridiculous to me
Please tell me I am doing something wrong? I can’t believe the language would evaluate the else when the if is true
EDIT
So it seems that the else condition is evaluated. So how do you get around a potential divide by zero error?
here’s the answer taken from :
http://www.sqlservercentral.com/Forums/Topic442497-150-1.aspx#bm1115960
Another option (especially if you’ve got a report with many expressions that could result in divide by zero situations is to use a Custom Code function.
In the Code tab/window of Report Properties, enter something like the following:
Public Function DivideBy(ByVal Exp1, ByVal Exp2)
If Exp2 = 0 Then
DivideBy = 0
Else : DivideBy = Exp1 / Exp2
End If
End Function
Then insert the expression
=code.DivideBy(Field!ToBeDivided.Value,Field!DividingBy.Value)
into any cell that has the potential for divide by zero problems.
Yes, both the true and false parts of an IIf function get evaluated:
http://en.wikipedia.org/wiki/IIf#Side_Effects