0

我的要求是编写一个在COUNTRIES表中添加值的过程。但是,首先它应该检查对应的值是否存在于另一个表中,REGIONS因为它是一个外键。仅当值存在时才允许插入到COUNTRIES表中。第二个要求是我不应该按原样country_idCOUNTRIES表中有重复的country_idPK。我写了这段代码,但它抛出了异常:

PLS-00103 Encountered the symbol "WHEN" when expecting one of the following:
begin case
PLS-00103:Encountered the symbol "WHEN" when expecting one of the following: ERROR

我的代码是:

create or replace procedure addi5 (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);
    end;

   BEGIN
     INSERT INTO countries(COUNTRY_ID, COUNTRY_NAME,REGION_ID)
     values (c_cntry_id, c_cntr_name,c_rgn_id);

   EXCEPTION
     WHEN dup_val_on_index THEN 
       c_cntry_id := null;
       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');

   ELSE
     WHEN dup_val_on_index
     THEN 
     c_cntry_id := null;

     DBMS_OUTPUT.PUT_LINE('Already present');
   END IF;

end addi5;
/

有人可以指导我做错了什么吗?或者如何编写或检查这两个条件?

4

1 回答 1

1

你自己的编码练习是不正确的。首先,如果可能,您应该尝试在 sql 中编写逻辑以提高可读性以及减少 sql 和 pl/sql 引擎之间的上下文切换。这是示例代码,您可能需要添加异常处理。

create or replace procedure addi5 (c_cntry_id in countries.country_id%type,
                                   c_cntr_name in countries.country_name%type, 
                                   c_rgn_id in countries.region_id%type)
is
begin
  insert into countries select c_cntry_id, c_cntr_name, c_rgn_id from dual
  where c_rgn_id in (select region_id from regions)
  and c_cntry_id not in (select country_id from countries);
  commit;
end;
/
于 2015-12-02T00:59:35.910 回答