Solved

T-SQL UDF - Divide By Zero

Posted on 2006-07-07
814 Views
Hi,

Having an issue with the Divide By Zero error whilst calculating a value in a SQL UDF.  Tried using the NULLIF and COALESCE functions, but can't seem to get them in the right context to stop the Divide By Zero.  Anyone help me out on this?  Thx.

Calculation:

@C32 = 0.0195
@C29 = 59
@C28 = 59
@C33 = 0.0193
@AnnualRealReturnStart = 0.039
@C16 = 0.0383

Set @C38 = Round( ((Power((1 + @C32) , (@C29 - @C28)) - 1) / @C33) / ((Power((1 + @AnnualRealReturnStart) , (@C29 - @C28)) - 1) / @C16) ,5)

becomes...

Set @C38 = Round( ((Power((1.0195) , 0)) - 1) / 0.0193) / ((Power((1.039) , 0)) - 1) / 0.0383) ,5)
0
Question by:simon_kirk
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points

LVL 143

Accepted Solution

Guy Hengel [angelIII / a3] earned 500 total points
ID: 17056737

declare @ONE numeric(10,4)
set @ONE = 1

Set @C38 = Round( ((Power((@ONE + @C32) , (@C29 - @C28)) - @ONE) / @C33) / ((Power((@ONE+ @AnnualRealReturnStart) , (@C29 - @C28)) - @ONE) / @C16) ,5)
0

LVL 14

Expert Comment

ID: 17056782
Set @C38 = case when ((Power((1 + @AnnualRealReturnStart) , (@C29 - @C28)) - 1) / @C16) <> 0 then Round( ((Power((1 + @C32) , (@C29 - @C28)) - 1) / @C33) / ((Power((1 + @AnnualRealReturnStart) , (@C29 - @C28)) - 1) / @C16) ,5) else 0 end
0

LVL 14

Author Comment

ID: 17056954
angelIII, that revised calculation works great, and now returns a NULL value rather than the error, but I'm intrigued as to why changing the 1 to a variable assigned the value of 1 stops the divide by zero error.
0

LVL 1

Expert Comment

ID: 17057104
Create another UDF called "DevByZeroSaver" which accepts one parameter.
The function returns 1 if 0 was given and otherwise return the given number.
Makes it more readable but it could have an impact on performance depending on your data amount.
0

Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

HIghlights of SSIS? 3 45
SQL - Subquery in WHERE section 4 34
SSIS Package Not Running in Batch File 3 18