2010-06-30 51 views
10
insert ignore into table1 
select 'value1',value2 
from table2 
where table2.type = 'ok' 

当我运行这个时,我得到错误“missing INTO keyword”。oracle插入如果行不存在

任何想法?

回答

17

因为IGNORE不是Oracle中的关键字。这是MySQL语法。

你可以做的是使用MERGE。

merge into table1 t1 
    using (select 'value1' as value1 ,value2 
      from table2 
      where table2.type = 'ok') t2 
    on (t1.value1 = t2.value1) 
when not matched then 
    insert values (t2.value1, t2.value2) 
/

从Oracle 10g我们可以使用合并而不处理两个分支。在9i中,我们不得不使用“虚拟”MATCHED分支。

在更古老的版本是唯一的选择要么:

  1. 测试该行的存在发出INSERT(或子查询)之前;
  2. 使用PL/SQL来执行INSERT并处理任何结果DUP_VAL_ON_INDEX错误。
8

因为您在“insert”和“into”之间输入了虚假词“ignore”!

insert ignore into table1 select 'value1',value2 from table2 where table2.type = 'ok' 

应该是:

insert into table1 select 'value1',value2 from table2 where table2.type = 'ok' 

从你的问题标题是“如果没有行存在甲骨文插入”我想你想“忽略”是一个Oracle的关键字,意思是“不要尝试插入行如果它已经存在“。也许这适用于其他一些DBMS,但它不在Oracle中。你可以使用一个MERGE语句,或者检查是否存在这样的:

insert into table1 
select 'value1',value2 from table2 
where table2.type = 'ok' 
and not exists (select null from table1 
       where col1 = 'value1' 
       and col2 = table2.value2 
       );