MS SQL Divide by Zero
SQLDivide by zero
Code
Dividing can be difficult due to NULLs and division by zero, here is a way to handle them simply.
Perform a / b, returning 0 if b=0:
ISNULL([a] / NULLIF([b],0),0) AS [c]
How this works
The first function NULLIF(x,y)
returns a null if x = y. Otherwise it returns x
The second function ISNULL(x,y)
simply returns x if not null, or y if x is null.
Our calculation says, if the denominator is 0, make it null.
Then a/null is null. So finally, if we get null, turn it back to 0.