使用DBMS_OUTPUT.put_line显示错误消息

问题描述 投票:0回答:1

我的要求是编写一个在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,它也没有显示相应的错误消息。有人可以指导吗?

oracle plsql exception-handling
1个回答
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;
/
© www.soinside.com 2019 - 2024. All rights reserved.