【问题标题】:Need assistance with IF Exists then Insert在 IF Exists 方面需要帮助,然后插入
【发布时间】:2013-07-17 12:18:09
【问题描述】:

我试图让它运行,但不知道为什么它不运行。我正在尝试创建一个 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;  

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

【问题讨论】:

  • 这最终将是一个过程,我现在只是把它写成一个块
  • 运行该代码时究竟发生了什么?
  • 请定义“不起作用”。至少您在FOR INDX... 语句之前缺少THEN。此外,我看不到 v_new_atty_id 在哪里被赋予了价值。

标签: sql oracle plsql exists


【解决方案1】:

也许根本不使用bulk 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);

【讨论】:

    【解决方案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;      
    

    【讨论】:

    • @user2405778 很高兴能为您提供帮助。不要忘记接受答案以避免低接受率并关闭问题。你也可以投票给答案;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 2014-02-06
    • 2017-11-02
    相关资源
    最近更新 更多