Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (20.3k points)

I have this error message:

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

What is the best way to write SQL code so that I will never see this error message again?

I could do either of the following:

  • Add a where clause so that my divisor is never zero

Or

  • I could add a case statement so that there is a special treatment for zero.

Is the best way to use a NULLIF clause?

Is there a better way, or how can this be enforced?

1 Answer

0 votes
by (40.7k points)

To avoid "Division by zero" error you should use the following code:

SELECT Case 

WHEN divisor=0 then null

ELSE dividend/divisor

End …

Or else to make it easier you can use this code given below:

SELECT dividend /NULLIF(divisor, 0) ...

Now, the only challenge is to remember the NULLIF bit, when you use the "/" key.

Related questions

Browse Categories

...