我想知道如果我的SUM工资是0,我怎么能得到一条消息。请检查我的代码:
DECLARE
v_sum_sal NUMBER(10,2);
v_deptno NUMBER NOT NULL := 10;
BEGIN
SELECT SUM(salary) -- group function
INTO v_sum_sal FROM employees
WHERE department_id = v_deptno;
IF v_sum_sal = 0 THEN
DBMS_OUTPUT.PUT_LINE ('You have selected 0 employees ');
else
DBMS_OUTPUT.PUT_LINE ('The sum of salary is ' || v_sum_sal);
end if;
END;
答案 0 :(得分:1)
如果没有匹配项,那么sum()
会返回NULL
,而不是0.这里有两种方法。
将查询更改为:
SELECT COALESCE(SUM(salary), 0) -- group function
INTO v_sum_sal FROM employees
WHERE department_id = v_deptno;
或者,将if
更改为:
IF v_sum_sal IS NULL THEN
答案 1 :(得分:0)
如果您的表中没有包含您提供的dept ID,代码中会发生什么。它将给出NULL输出。因此,如果你设置一个异常处理条件,它将像魅力一样工作。
DECLARE
v_sum_sal NUMBER(10,2);
v_deptno NUMBER NOT NULL := 10;
BEGIN
BEGIN
SELECT SUM(salary) -- group function
INTO v_sum_sal
FROM employees
WHERE department_id = v_deptno;
EXCEPTION
WHEN NO_DATA_FOUND THEN
v_sum_sal:=0;
END;
IF v_sum_sal = 0 THEN
DBMS_OUTPUT.PUT_LINE ('You have selected 0 employees ');
ELSE
DBMS_OUTPUT.PUT_LINE ('The SUM OF salary
IS
' || v_sum_sal);
END IF;
END;