How to protect sql statement from Divide By Zero error

烂漫一生 提交于 2019-12-04 09:22:18

Use a case statement.

SELECT 
CASE WHEN COUNT(broken_cones) = 0 then 0
ELSE CAST(NULLIF((.01 * 2500)/Count(broken_cones), 0) AS decimal(7,4)) END
FROM [ice].[ice_cream_inventory] WHERE broken_cones = 'Yes'

You already have a solution, but this is why your original solution didn't work.

Your NULLIF needs to be moved in order to be effective. It is doing the division before it gets to the NULLIF call. Dividing by null will return a null value.

SELECT CAST((.01 * 2500)/NULLIF(Count(broken_cones), 0) AS decimal(7,4)) 
FROM [ice].[ice_cream_inventory] 
WHERE broken_cones = 'Yes'`

The NULLIF() function is a great way to prevent divide by zero, since anything divide by NULL returns null. The way to use it is as follows:

<expression> / NULLIF( <expression>, 0 )

Unfortunately you've wrapped your whole divide expression in NULLIF() which is why it isn't working for you. So step one is to get it to return NULL if your COUNT() comes back zero:

SELECT
    (0.01 * 2500) / NULLIF( COUNT(broken_cones), 0 )
FROM [ice].[ice_cream_inventory]
WHERE broken_cones = 'Yes'

Now you said you wanted that NULL to come back zero? That is where you use ISNULL():

ISNULL(<expression1>, <expression2>)

If the first expression is NULL then return the second expression, so our SQL now becomes:

SELECT 
    ISNULL(
        (0.01 * 2500) / NULLIF( COUNT(broken_cones), 0 ),
        0
    )
FROM [ice].[ice_cream_inventory]
WHERE broken_cones = 'Yes'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!