2010-06-30 92 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 
       );