2013-07-18 67 views
1

即時通訊嘗試讓這個運行,但無法弄清楚爲什麼它不是。我想創建一個PL/SQL塊,將在2碼讀取和插入之前,確保它們的存在:需要援助與IF存在,然後插入

declare 
    v_old_atty_id in atty_rules.attorney_id%type; 
    v_new_atty_id in atty_rules.attorney_id%type; 

    type rule_array is varray(10000) of number; 
    v_rule rule_array; 
begin 

    select distinct rule_id 
    bulk collect into v_rule 
    from atty_rules 
    where attorney_id = v_old_atty_id 
    and date_activated <= sysdate 
    and sysdate < nvl(date_deactivated, sysdate+1); 

    if exists (select attorney_id 
      from ORG_ATTYS 
      where attorney_id = v_new_atty_id) 
      for indx in 1..v_rule.count 
      loop 
       insert into atty_rules (attorney_id,rule_id) 
       values (v_new_atty_id, v_rule(indx)); 
      end loop 
    else 
     dbms_output.put_line('Doesnt exist') 
    end if;  
end; 

任何方向將會有很大的幫助,謝謝。

+0

這最終將是一個過程,即時將它作爲一個塊現在 – user2405778

+0

當你運行代碼時會發生什麼? –

+0

請定義「不起作用」。至少在「FOR INDX ...」聲明之前,你錯過了「THEN」。另外,我沒有看到'v_new_atty_id'曾經給過什麼值。 –

回答

2

試試這個方法:

select count(attorney_id) 
into v_count 
from ORG_ATTYS 
where attorney_id = v_new_atty_id 

if v_count > 0 then 
     for indx in 1..v_rule.count 
     loop 
      insert into atty_rules (attorney_id,rule_id) 
      values (v_new_atty_id, v_rule(indx)); 
     end loop 
else 
    dbms_output.put_line('Doesnt exist') 
end if;  
+0

太棒了,非常感謝 – user2405778

+0

@ user2405778我很高興我可以幫助你。不要忘記接受答案,以避免低接受率,並結束問題。你也可以爲答案投票;) – Parado

1

也許不使用散裝夾頭可言,只是做在一個SQL語句,像這樣:

v_old_atty_id := ... 
v_new_atty_id := ... 

insert into atty_rules (attorney_id,rule_id) 
select v_new_atty_id, rule_id 
from ( 
    select distinct rule_id 
    from atty_rules 
    where attorney_id = v_old_atty_id 
     and date_activated <= sysdate 
     and sysdate < nvl(date_deactivated, sysdate+1 
) 
WHERE exists (select attorney_id 
      from ORG_ATTYS 
      where attorney_id = v_new_atty_id);