Groups | Blog | Home
all groups > sql server new users > may 2005 >

sql server new users : divide by zero error


r
5/31/2005 9:29:23 AM
How can I avoid this?

I have the following calculations in a view:

Data017_all.MTD_StkOrdAmt / Data017_all.MTD_TotOrdAmt * 100 AS MTD_OSO,
Data017_all.YTD_StkOrdAmt / Data017_all.YTD_TotOrdAmt * 100 AS YTD_OSO,


....if the second number (the _TotOrdAmt) is 0, I get the divide by zero
error. Is there some way to write this so that if that number is 0 the
resulting value is 0 and not an error???

Thanks in advance...

r
5/31/2005 9:59:01 AM
Got it ...

need to use CASE.

[quoted text, click to view]

Roman JR.
5/31/2005 3:59:25 PM
Sorry my bad:

here is code that acutally works :)

ISNULL((Data017_all.MTD_StkOrdAmt/(CASE WHEN Data017_all.MTD_TotOrdAmt = 0
THEN NULL ELSE Data017_all.MTD_TotOrdAmt END)) *100, 0)

let me know if this code worked for you.

Regards,

Roman JR.

[quoted text, click to view]
Roman JR.
5/31/2005 4:21:40 PM
Hi,

You can do something like this

ISNULL((Data017_all.MTD_StkOrdAmt/CASE WHEN Data017_all.MTD_TotOrdAmt = 0
THEN NULL END)*100, 0)

Basically, covevert the 0 to NULL, this way you will avoid Divide by zero
error.
Then if the result of devision is NULL, use ISNULL to convert the NULL value
to 0

That is it.

Roman JR.

[quoted text, click to view]
Hugo Kornelis
5/31/2005 10:29:27 PM
[quoted text, click to view]

Hi R,

Apart from using CASE< you can also use a shorthand form with NULLIF and
COALESCE:

SELECT COALESCE(Data017_all.MTD_StkOrdAmt /
NULLIF(Data017_all.MTD_TotOrdAmt, 0) * 100, 0) AS MTD_OSO,
COALESCE(Data017_all.YTD_StkOrdAmt /
NULLIF(Data017_all.YTD_TotOrdAmt, 0) * 100, 0) AS YTD_OSO

Best, Hugo
--

AddThis Social Bookmark Button