Link to home
Start Free TrialLog in
Avatar of Erin Leale
Erin LealeFlag for United States of America

asked on

SSRS "If - then - else" formula #error

Hello!
I'm new to SSRS - using - Report Builder 3 with Epicor.  I have a formula that should prevent a divide by 0 error.  

=iif(Fields!Calculated_Inv_Margin.Value = 0, 0,
sum(Fields!Calculated_Inv_Margin.Value)/sum(Fields!Calculated_Revenue.Value))

It does the percent calc great - but anything with a 0 gets an #Error.  So I took out the divide calc and just had the revenue field show - that works.  Why doesn't the the calc above just give me a 0?

User generated image
User generated image
Any help would be great!  Thank you! 
Avatar of Andrei Fomitchev
Andrei Fomitchev
Flag of United States of America image

You can modify SELECT:

-- Test data
DECLARE @t TABLE (val1 Int, val2 Int);
INSERT INTO @t VALUES (10,0),(20,0);
SELECT * FROM @t;




User generated image

SELECT Sum(val1)/Sum(val2) FROM @t;

Msg 8134, Level 16, State 1, Line 6
Divide by zero error encountered.

;WITH cte (p1, p2) AS (
   SELECT Sum(val1) AS p1, Sum(val2) AS p2 FROM @t
)
SELECT CASE WHEN p2=0 THEN 0.0 ELSE p1/p2 END AS pp FROM cte

User generated image
(value / "divide by")  has "divide by" zero error ( or more formally )
(numerator / denominator)  has divide by zero error

You need to test if the denominator is zero (your existing formula tests the numerator)

=iif(sum(Fields!Calculated_Revenue.Value) = 0, 0,
sum(Fields!Calculated_Inv_Margin.Value)/sum(Fields!Calculated_Revenue.Value))

note: you also need to test the summed value, just like you have used in the calculation


Avatar of Erin Leale

ASKER

So I tried the following:

=iif(sum(Fields!Calculated_Revenue.Value) <> 0, sum(Fields!Calculated_Inv_Margin.Value)/sum(Fields!Calculated_Revenue.Value),0)

This Produces the same result:



User generated image
I tested the value by using the following:
=iif (Sum(Fields!Calculated_Revenue.Value) = 0, 0, 1)

This returned the result I expected:
User generated image
I don't understand it - it seems like it is re-evaluating the formula after "then" in the if statement.

I also tried this:
 =iif (Sum(Fields!Calculated_Inv_Margin.Value) = 0, 0,
sum(Fields!Calculated_Inv_Margin.Value)/sum(Fields!Calculated_Revenue.Value))
User generated image
I'm going to try and store a formula with the 0 result to see if I can make it work that way.  

Can you do a case statement in SSRS formula editor?  

Thanks! 
ASKER CERTIFIED SOLUTION
Avatar of Erin Leale
Erin Leale
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial