Oracle 使用DBMS_OUTPUT.put_行显示错误消息
我的要求是编写一个程序,在Oracle 使用DBMS_OUTPUT.put_行显示错误消息,oracle,plsql,exception-handling,Oracle,Plsql,Exception Handling,我的要求是编写一个程序,在国家/地区表中添加值。但是,首先它应该检查另一个表中是否存在相应的值,REGIONS,因为它是一个外键。仅当值存在时,才允许插入国家/地区表。否则,不会 我写了一段代码,工作很好: create or replace procedure addi3 (c_cntry_id in out countries.country_id%type, c_cntr_name in countries.count
国家/地区
表中添加值。但是,首先它应该检查另一个表中是否存在相应的值,REGIONS
,因为它是一个外键。仅当值存在时,才允许插入国家/地区
表。否则,不会
我写了一段代码,工作很好:
create or replace procedure addi3 (c_cntry_id in out countries.country_id%type,
c_cntr_name in countries.country_name%type,
c_rgn_id in countries.region_id%type)
is
region_exists pls_integer;
begin
begin
select 1 into region_exists
from regions r
where r.region_id = c_rgn_id;
exception
when no_data_found then
region_exists := 0;
DBMS_OUTPUT.PUT_LINE('Already present');
end;
if region_exists = 1 then
insert into countries(country_id, country_name,region_id)
values (c_cntry_id, c_cntr_name,c_rgn_id);
DBMS_OUTPUT.PUT_LINE('Inserted');
end if;
end addi3;
/
它工作正常,只是如果我通过提供一个在regions表中不存在的
region\u id
来执行该过程,它就不会正确地在countries表中插入。但是,我想通过使用DBMS\u输出抛出一个错误来增强它。如果region\u id
不存在,并且即使我有DBMS\u输出。put\u line
,它也不会显示适当的错误消息。有人能帮你指导吗?根据你的请求在评论中编辑你的代码:
create or replace procedure addi3 (c_cntry_id in out countries.country_id%type,
c_cntr_name in countries.country_name%type,
c_rgn_id in countries.region_id%type)
is
region_exists pls_integer;
begin
begin
select 1 into region_exists
from regions r
where r.region_id = c_rgn_id;
exception
when no_data_found then
region_exists := 0;
DBMS_OUTPUT.PUT_LINE('Region not present '||sqlerrm);
-- uncomment the RAISE if you want the exception to be
-- propagated back to the calling code.
--RAISE;
end;
-- if you uncommented the RAISE the IF here is redundant
-- because you wouldn't have got here if the region didn't exist.
if region_exists = 1 then
insert into countries(country_id, country_name,region_id)
values (c_cntry_id, c_cntr_name, c_rgn_id);
DBMS_OUTPUT.PUT_LINE('Inserted');
end if;
end addi3;
/
会话是否打开了服务器输出?如果没有,则必须手动获取“已存在”或“已插入”消息。是的,我在执行过程之前设置了:“打开服务器设置”。当您说希望它“抛出错误”时,您的意思是希望它说除当前“已存在”之外的内容吗?或者它真的引发了一个异常并退出了程序?是的,在我的情况下,当区域id不存在时,说“已经存在”(实际上,它应该是“不存在”,但我想,如果该区域不存在,一旦错误消息可见,就可以更正它了——这不是应该在该区域进行插入的时候吗?