0

COUNTRIES私の要件は、テーブルに値を追加する手順を書くことです。REGIONSただし、これは外部キーであるため、最初に対応する値が別のテーブルに存在するかどうかを確認する必要があります。値が存在する場合のみ、テーブルへの挿入がCOUNTRIES許可されます。country_id2 番目の要件は、 in COUNTRIEStable as country_idisの値が重複してはならないということですPK。私はこのコードを書きましたが、例外をスローしています:

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;
/

誰かが私が間違っていることを教えてもらえますか? または、これら2つの条件をどのように記述または確認するのですか?

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 に答える