Friday, February 17, 2017

ORA-01476: divisor is equal to zero


-- Correct your code so that you do not divide a number by zero.

To calculate percentage between field1 and field 2
1
SELECT ((FIELD1/FIELD2) *100) as Percentage from TableA;
Now since the value of FIELD2 contains zero and any number divided by zero is infinity. So this will throw the exception:
1
2
ERROR at line 1:
ORA-01476: divisor is equal to zero
So how do you solve this. There are many ways to handle this error in Oracle.
1. The first and foremost way is to enforce the business logic and try to ensure that the field doesn’t contain a 0 in the first place.
2. Use the DECODE function
1
DECODE(FIELD2,0,0,((FIELD1/FIELD2)*100))

 This will return 0 in case the divisor is set to 0
3.User ZERO_DIVIDE to handle a zero divisor error
In PL/SQL you can trap the error using ZERO_DIVIDE option. The best way to do it is replace the zero with a very small value like 0.00001
1
2
3
4
EXCEPTION
WHEN ZERO_DIVIDE THEN
:field2_var := 0.00001;
END;
Or alternately you can replace the output of the divide by zero equation with a zero return value.
1
2
3
4
EXCEPTION
WHEN ZERO_DIVIDE THEN
return 0;
END;

SELECT 
((COUNT(DECODE(SUBSTR(A.ASSETNUM,6,3),'ACS','ACS',0,null))/COUNT(DECODE(SUBSTR(A.PMNUM,1,3),'ACS','ACS',0,null)))*100)
FROM WORKORDER A
WHERE TO_CHAR(A.REPORTDATE,'MON-YYYY') = :WO_DATE;
 

No comments:

Post a Comment

To generate a PDF using JavaScript in Oracle APEX from a collection

  To generate a PDF using JavaScript in Oracle APEX from a collection, you can follow these steps: 1. Create a button or link on your APEX p...