-1

I have an error coming up "Divide by zero error encountered." in SQL Server 2005. I understand that i have few rows that are are getting divided by Zero that results in this error. So i was wondering if can eliminate this error when the divisor is zero. if the divisor is 0, it should return 0. How can i do that?

sum(isnull(cast(S.S_AmountCollected as numeric(10, 2)), 0)) / sum(isnull(cast(S.AmountSold as numeric(10, 2)), 0)) 

Thank you!

1

2 Answers 2

1

Use a CASE statement:

CASE WHEN SUM(ISNULL(CAST(S.AmountSold as numeric(10, 2)), 0) = 0
        THEN 0
      ELSE 
        SUM(ISNULL(CAST(S.S_AmountCollected as numeric(10, 2)), 0)) 
           / 
        SUM(ISNULL(CAST(S.AmountSold as numeric(10, 2)), 0))
     END
Sign up to request clarification or add additional context in comments.

4 Comments

I believe he has an error when the value is 0, not null, but the solution you show will still work with a small change
yeah.. it was hard to untangle his one-liner.. :)
CASE works great! Thank you Miky! :-)
The page wont let me accept an answer for 10 minutes after the post. Hmmm :-)
0

You can not eliminate this error as an integer divided by 0 has undefined value. You will have to add an explicit check to have the behavior you expect.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.