Search code examples
sqloracle-databaseprocedure

Oracle [Procedure] - Sum function ignores WHERE clause


I have a problem with a ORACLE Procedure, it seems that SELECT SUM ignores my WHERE clause, and Sums up ALL of the columns instead of only those that i want to (deptno). However if i use one of this functions like this for example :

select SUM(SAL) AS SALSUM FROM SCOTT.EMP WHERE SCOTT.EMP.DEPTNO = 10;

It displays the proper SUM. What may be the problem? Thanks for help.

CREATE OR REPLACE PROCEDURE PROCEDURE1(numerdept IN number, money OUT number) IS
    SALSUM NUMBER;
    COMMSUM NUMBER;
WYJATEK EXCEPTION;
BEGIN
    IF numerdept IN (10, 20, 30) THEN
    BEGIN
        select SUM(SAL) INTO SALSUM FROM SCOTT.EMP WHERE SCOTT.EMP.DEPTNO = numerdept;
        select SUM(COMM) INTO COMMSUM FROM SCOTT.EMP WHERE SCOTT.EMP.DEPTNO = numerdept;
        money := SALSUM + COMMSUM;
    END;
    ELSE RAISE WYJATEK;
    END IF;

    EXCEPTION 
    WHEN WYJATEK THEN
    BEGIN
    dbms_output.put_line('Wrong deptno');
    money := NULL; 
    END;
END;
-- checking -- 
SET SERVEROUTPUT ON;
DECLARE
    pension number;
BEGIN
    PROCEDURE1(10, pension);
    dbms_output.put_line(pension);
END;

[EDIT 3] SOLUTION

select NVL(SUM(SAL), 0) INTO SALSUM FROM SCOTT.EMP WHERE SCOTT.EMP.DEPTNO = numerdept;
select NVL(SUM(COMM), 0) INTO COMMSUM FROM SCOTT.EMP WHERE SCOTT.EMP.DEPTNO = numerdept;

AND

 BEGIN
    dbms_output.put_line('Wrong deptno');
    money := 10; 
END;

Solution

  • Your problem is that your input parameter has the same name as your column, so when the query sees

    WHERE SCOTT.EMP.DEPTNO = deptno
    

    it interprets deptno as SCOTT.EMP.DEPTNO, meaning that it is true for all values of deptno. Change the name of your input parameter and the query will work as expected.

    You should also use NVL to ensure that the individual SUM values are not NULL, as if either of them is NULL that will make the sum of them NULL as well i.e.

    select NVL(SUM(SAL), 0) INTO SALSUM FROM SCOTT.EMP WHERE SCOTT.EMP.DEPTNO = numerdept;
    select NVL(SUM(COMM), 0) INTO COMMSUM FROM SCOTT.EMP WHERE SCOTT.EMP.DEPTNO = numerdept;