-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!

challengeAccepted
  • 7,106
  • 20
  • 74
  • 105
  • 1
    Use `case` to detect the 0 value and not run the division. http://msdn.microsoft.com/en-us/library/ms181765.aspx – asawyer Feb 20 '13 at 16:36

2 Answers2

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
Mike Dinescu
  • 54,171
  • 16
  • 118
  • 151
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.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176