J KSS
J KSS

Reputation: 3

SQL case Statement to handle "divide by zero" ignores condition THEN 0

Here is the SQL:

CASE 
    WHEN Field1 = 0 THEN 0 
    ELSE SUM((Field1 - Field2 * Field3)/Field1) 
END

This and variations of it return the divide by zero error every time Field1 = 0

Need to look away, I'm sure the answer is obvious.

Thanks

Upvotes: 0

Views: 1028

Answers (1)

Simon1979
Simon1979

Reputation: 2108

Try wrapping the sum on the outer:

sum(CASE WHEN Field1 = 0 THEN 0 ELSE ((Field1 - Field2 * Field3)/Field1) END)

Upvotes: 7

Related Questions