开发者

T-SQL 2005 - Divide by zero error encountered

开发者 https://www.devze.com 2023-01-02 02:45 出处:网络
I am trying to get some percentage data from a stored procedure using code similar to the line below. Obviously this is going to cause a (Divide by zero error encountered) problem when base.[XXX_DataS

I am trying to get some percentage data from a stored procedure using code similar to the line below. Obviously this is going to cause a (Divide by zero error encountered) problem when base.[XXX_DataSetB] returns 0 which may happen some of the time.

Does anyone know how i can deal with this in the most efficient manner?

Note: There would be about 20+ lines looking like the one below...

cast((base.[XXX_DataSetB] - base.[XXX_Da开发者_运维百科taSetA]) as decimal) / 
                            base.[XXX_DataSetB] as [XXX_Percentage]


I guess it depends on what behaviour you expect when XXX_DataSetB is zero.

If you don't want any rows returned that might cause an error, you can easily filter out those rows by adding where XXX_DataSetB <> 0 to your query.

If you would like problem rows to be NULL then you could use a case statement, or something like this:

cast(([XXX_DataSetB] - [XXX_DataSetA]) as decimal) / nullif([XXX_DataSetB], 0)


I'd force the average to null by making the bottom term null instead of zero:

cast((base.[XXX_DataSetB] - base.[XXX_DataSetA]) as decimal) 
     / case when base.[XXX_DataSetB] = 0 then null 
         else base.[XXX_DataSetB] end as [XXX_Percentage] 
0

精彩评论

暂无评论...
验证码 换一张
取 消