我的要求是编写一个在COUNTRIES
表中添加值的过程。但是,首先它应检查另一个表REGIONS
中是否存在相应的值,因为它是外键。仅当值存在时才允许插入COUNTRIES
表。否则,没有。
我写了一段代码并且工作正常:
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;
/
它运行正常,但是如果我通过提供区域表中不存在的region_id
来执行该过程,则它在country表中没有正确插入。但是,如果DBMS_OUTPUT.put_line
不存在,我希望使用region_id
抛出错误来增强它,即使我有DBMS_OUTPUT.put_line
,也不会显示相应的错误消息。有人可以指导吗?
答案 0 :(得分:0)
根据您的请求在评论中编辑代码:
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;
/