用于插入非重复值和外键约束注意事项的Oracle存储过程

时间:2015-12-01 20:30:41

标签: oracle plsql foreign-key-relationship pls-00103

我的要求是编写一个在COUNTRIES表中添加值的过程。但是,首先它应检查另一个表REGIONS中是否存在相应的值,因为它是外键。仅当值存在时才允许插入COUNTRIES表。第二个要求是,country_id表中的COUNTRIES不应具有重复值,因为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;
/

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

1 个答案:

答案 0 :(得分:0)

你自己的编码练习是不正确的。首先,如果可能的话,您应该尝试在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;
/