Simple way to prevent a Divide By Zero error in SQL

前端 未结 5 1289
陌清茗
陌清茗 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:57

    In my opinion the CASE statement is exactly the way to go. Rather than calculating something you state the value to return for the case that AttTotal is zero. You could even add another case branch for 0 of 0 being 100%.

    Just a side note: I would not return 0 when AttTotal is zero and ClubTotal is greater than zero. NULL might be more appropriate. Or you would create strings (e.g. '10.50%') rather than numbers (e.g. 10.5%), containing "No att. total" in case AttTotal is zero:

    PercentageString :=
      CASE
        WHEN AttTotal = 0 AND ClubTotal = 0 then '100%'
        WHEN AttTotal = 0 AND ClubTotal <> 0 THEN 'No att. total'
        ELSE to_char(ClubTotal / AttTotal * 100) || '%'
      END;
    

提交回复
热议问题