Oracle [Procedure] - Sum function ignores WHERE clause

穿精又带淫゛_ 提交于 2021-02-17 05:32:06

问题


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;

回答1:


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;


来源:https://stackoverflow.com/questions/60021862/oracle-procedure-sum-function-ignores-where-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!