Simple way to prevent a Divide By Zero error in SQL

前端 未结 5 1231
陌清茗
陌清茗 2021-02-05 17:15

I have a SQL query which used to cause a

Divide By Zero exception

I\'ve wrapped it in a CASE statement to stop this fr

5条回答
  •  醉梦人生
    2021-02-05 17:36

    The solution that I found to handle the divide by zero problem is to create a function that I can call upon to deal the situation, as I often have to perform some sort of ratio/ percentage type analysis. Here's the simple function that I wrote.

    Create Function fnRatio(@Numerator decimal(10,2),@Demoninator decimal(10,2))
    
    Returns decimal(10,2)
    
    Begin
    
    Return
    
    Case 
    
          When @Demoninator = 0 then 0.00 
    
    
    
          When @Demoninator Is Null then Null
    
    
    
    Else
    
          @Numerator/@Demoninator
    
    End 
    

    End

    Regards

    Jason

提交回复
热议问题