MS SQL处理“分子分母都有除法式”方法,避免devide by zero error:
eg:
有4列值,分别为A,B,C,D.我们需要求(A/B)/(C/D)的值作为新的一列。 只用ISNULL处理,可能会报错devide by zero error.
解决方法/solution:
SELECT
CASE WHEN COALESCE(A/ NULLIF(B,0), 0) = 0 OR COALESCE(C / NULLIF(D,0), 0) = 0 THEN 0 ELSE (A/B)/(C/D) END AS NewColumn
根据实际情况,可在外面再加ISNULL,CAST函数。
说明:SELECT COALESCE(dividend / NULLIF(divisor,0), 0) FROM sometable
For every divisor that is zero, you will get a zero in the result set.
引用:http://stackoverflow.com/questions/861778/how-to-avoid-the-divide-by-zero-error-in-sql