需要IF存在然后插入的帮助

时间:2013-07-18 13:49:08

标签: sql oracle plsql exists

我试图让它运行,但无法弄清楚为什么它不。我正在尝试创建一个pl / sql块,它将读入2个代码并确保它们在插入之前存在:

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;  

任何方向都会有很大帮助,谢谢。

2 个答案:

答案 0 :(得分: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;      

答案 1 :(得分:1)

也许根本不使用批量collet,只需在一个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);