oracle如果行不存在则插入

时间:2010-06-30 09:13:16

标签: sql oracle insert

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

当我运行此操作时,我收到错误“缺少INTO关键字”。

有什么想法吗?

3 个答案:

答案 0 :(得分:21)

  

当我运行此操作时,我收到错误“缺少INTO关键字”。

因为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开始,我们可以在不处理两个分支的情况下使用merge。在9i中,我们不得不使用“虚拟”MATCHED分支。

在更古老的版本中,唯一的选择是:

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

答案 1 :(得分:8)

因为您在“插入”和“进入”之间键入了虚假词“忽略”!!

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 insert if if row not exists”我假设你认为“ignore”是一个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
               );

答案 2 :(得分:7)

请注意,如果您有幸使用版本11g第2版,则可以使用提示 IGNORE_ROW_ON_DUPKEY_INDEX

从文档中: http://download.oracle.com/docs/cd/E11882_01/server.112/e10592/sql_elements006.htm#CHDEGDDG

我博客的一个例子: http://rwijk.blogspot.com/2009/10/three-new-hints.html

此致 罗布。

相关问题