sqlsql-serversql-server-2008sql-server-2005dividebyzeroexception

How to avoid the "divide by zero" error in SQL?


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:

Or

Is the best way to use a NULLIF clause?

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


Solution

  • In order to avoid a "Division by zero" error we have programmed it like this:

    Select Case when divisor=0 then null
    Else dividend / divisor
    End ,,,
    

    But here is a much nicer way of doing it:

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

    Now the only problem is to remember the NullIf bit, if I use the "/" key.