Merge into的注意点之ORA-30926

来源:互联网 发布:php数据库输出乱码 编辑:程序博客网 时间:2024/03/29 12:57
大家可以看看: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 行已合并。

  ---------------这回就何合并成功了。          

整理自网络                                      

0 0
原创粉丝点击