如果表中有任何K状态,我需要返回。当没有K状态时,它不返回任何行,因此INTO部分给出错误。因此,我添加了一个异常,最后得到0 status_count,但这次在plsql块结束时有一个最后的异常。
当查询返回没有行时我应该返回0还是我需要处理2个例外?有什么建议吗?
BEGIN
SELECT COUNT(1) INTO v_status_count
FROM tablename
WHERE STATUS = 'K'
AND ACCOUNT_NUMBER = o_account_number
GROUP BY STATUS;
EXCEPTION WHEN NO_DATA_FOUND THEN
v_status_count := 0;
IF v_status_count > 0 THEN
o_status := 'Y';
END IF;
EXCEPTION WHEN OTHERS THEN
o_result := 1;
END;
答案 0 :(得分:1)
请不要试图实现,但
DECLARE
v_status_count NUMBER :=0;
BEGIN
SELECT COUNT(1) INTO v_status_count
FROM tablename
WHERE STATUS = 'K'
AND ACCOUNT_NUMBER = o_account_number
GROUP BY STATUS;
EXCEPTION
WHEN NO_DATA_FOUND THEN
v_status_count := 0;
WHEN OTHERS THEN
o_result := 1;
END;
答案 1 :(得分:1)
删除group by
子句,在这种情况下不需要
答案 2 :(得分:0)
不幸的是,你有点不清楚你在寻找什么。在下面的示例中,我假设您想知道数据库中是否存在帐号和状态组合。
数据设置
create table accounts (
account_number number,
status varchar2(1)
);
insert into accounts values (1, 'K');
insert into accounts values (2, 'L');
select * from accounts;
ACCOUNT_NUMBER S
-------------- -
1 K
2 L
<强>程序强>
create or replace procedure get_account_status(
p_account_number in number,
p_status in varchar2,
o_status out varchar2,
o_result out number
) is
v_count number;
begin
-- the select that never throws:
-- v_count = 0 if no account with requested status found
-- v_count = 1 if at least one row with account and status is found
-- note rownum = 1 is valid restriction as it's enough to know that at least
-- one row exists
select count(*)
into v_count
from accounts
where status = p_status
and account_number = p_account_number
and rownum = 1;
-- adjust the return/output value(s) as you like
if v_count = 1 then
o_status := 'Y';
o_result := 1;
else
o_status := 'N';
o_result := 0;
end if;
end;
/
show errors
测试块和结果
declare
v_status varchar2(1);
v_result number;
begin
get_account_status(1, 'K', v_status, v_result);
dbms_output.put_line('v_status = ' || v_status ||
'; v_result = ' || v_result);
get_account_status(2, 'K', v_status, v_result);
dbms_output.put_line('v_status = ' || v_status ||
'; v_result = ' || v_result);
get_account_status(3, 'K', v_status, v_result);
dbms_output.put_line('v_status = ' || v_status ||
'; v_result = ' || v_result);
end;
/
v_status = Y; v_result = 1
v_status = N; v_result = 0
v_status = N; v_result = 0
PL/SQL procedure successfully completed.