oracle 中的 No_Data_found 异常
Posted
技术标签:
【中文标题】oracle 中的 No_Data_found 异常【英文标题】:No_Data_found exception in oracle 【发布时间】:2019-10-13 19:56:19 【问题描述】:我有两个数据库表(account 和 account1)。我想输入一个帐号并首先检查是否 帐号是否在帐户表中。如果它不在帐户表中,则引发异常并检查 account1 表。代码适用于此。但是如果我想在 account1 表中也找不到帐号时显示错误消息,那么我该怎么办。 这是我的部分代码-
BEGIN
begin
select Balance,Cid
into cur_balance,cl_id
from Account
where Accno = x;
select max(Tid) into id from(select Tid from trnsaction union select Tid from trnsaction1);
id:=id+1;
ac_branch := 'mirpur';
exception
when no_data_found then
select Balance,Cid
into cur_balance,cl_id
from account1
where accno = x;
select max(Tid) into id from(select Tid from trnsaction union select Tid from trnsaction1);
id:=id+1;
ac_branch := 'gulshan';
end;
【问题讨论】:
【参考方案1】:你可以使用
raise_application_error(-20001,'None of the tables contain this account !');
或
dbms_output.put_line('None of the tables contain this account !');
在Account
表的最后一个引发异常语句中:
DECLARE
cur_balance Account.Balance%type;
cl_id Account.Cid%type;
id trnsaction.Tid%type;
BEGIN
begin
select Balance, Cid
into cur_balance, cl_id
from Account
where Accno = x;
ac_branch := 'mirpur';
exception
when no_data_found then
select Balance, Cid
into cur_balance, cl_id
from Account1
where accno = x;
ac_branch := 'gulshan';
exception
when no_data_found then
raise_application_error(-20001,'None of the tables contain this account !');
end;
begin
select max(Tid)
into id
from (select Tid
from trnsaction
union
select Tid from trnsaction1);
id := id + 1;
exception
when no_data_found then null;
end;
END;
Account
与 Account1
的列类型以及 trnsaction1
与 trnsaction
表的列类型被认为是相对相同的。
如果您更喜欢使用dbms_output.put_line
,请在它之前发出命令set serveroutput on
。
顺便说一句,无需重复独立于我们感兴趣的查询的其他查询。
【讨论】:
【参考方案2】:为什么不union all
和row_number
?
begin
Select Balance,Cid, branch
into cur_balance,cl_id, ac_branch
from
(Select Balance,Cid, branch
row_number()
Over (order by seq) as rn
From
(select Balance,Cid, 1 as seq, 'mirpur' as branch
from Account
where Accno = x
Union all
select Balance,Cid, 2 as seq, 'gulshan' as branch
from account1
where accno = x))
Where rn = 1;
select max(Tid) into id from(select Tid from trnsaction union select Tid from trnsaction1);
id:=id+1;
exception
when no_data_found then
Null; -- or dbms_output.put_line('acct not found');
end;
/
干杯!!
【讨论】:
以上是关于oracle 中的 No_Data_found 异常的主要内容,如果未能解决你的问题,请参考以下文章
为啥 no_data_found ORA-01403 在 Oracle 中是一个异常?
在使用oracle创建存储过程部分代码: EXCEPTION WHEN NO_DATA_FOUND THEN NULL; WHEN OTHERS THEN RAISE;