1. 程式人生 > 其它 >Merge into的注意點之ORA-30926: 無法在源表中獲得一組穩定的行?

Merge into的注意點之ORA-30926: 無法在源表中獲得一組穩定的行?

原文地址:https://blog.csdn.net/ytfy12/article/details/52488797

轉自:http://blog.itpub.net/29900383/viewspace-1284128/

大家可以看看:http://blog.sina.com.cn/s/blog_5d25646e0100qu17.html的內容,然後我再補充一點:

新建兩張table :test_source和test_target,他們的資料分別如下:                  
SQL> select * from test_source;
NAME               ID
---------- ----------
P3              74834
P4              74835
luo                8
P1              74832
P2              74833
zhi                8
SQL> select name ,id from test_target;
NAME       ID
---------- ----------
P3***           74834
P4***           74835
luo**             8
P1***           74832
P2***           74833
zhi**             8
SQL>  merge into test_target
  2   using test_source
  3   on (test_source.id = test_target.id)
  4   when matched then update set test_target.name = test_source.name
  5  when not matched then insert values(test_source.name,test_source.id);
 using test_source
       *
第 2 行出現錯誤:
ORA-30926: 無法在源表中獲得一組穩定的行
---------------------哈哈,報錯了,大家想想為什麼呢?-----------------------------
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
解答如下:
首先我們要知道merge into存在的意義是什麼!!!
      使用merge into是為了根據匹配條件on(condition)利用table_source 的資料更新合併table_target的資料。
merge into的內部處理是將table_source的每一條記錄和table_target的每一條記錄對比匹配,匹配到符合條件的記錄就會進行修改,匹配不到的話就會insert。如果table_source的匹配列中有重複值的話,等到第二次重複的列值匹配的時候,就會將第一次的update後的值再一次update,就是說合並後的table_target中會丟失在table_source中的記錄!!!如果記錄丟失的話,兩表合併的意義何在?!!因此我們使用merge into要注意:源表匹配列中不能有重複值,否則無法匹配(報錯!     )。  
 -----------------------------------------------------------------------------------------------------------------我們可以上面將重複的列值去掉試試:
                                                              SQL> delete from test_source where name = 'zhi';
已刪除 1 行。
SQL>  merge into test_target
  2   using test_source
  3   on (test_source.id = test_target.id)
  4   when matched then update set test_target.name = test_source.name
  5  when not matched then insert values(test_source.name,test_source.id);
6 行已合併。
---------------這回就何合併成功了。