民主和自由是我们永恒的追求

merge into的使用

上一篇 / 下一篇  2008-07-17 16:09:22

如果存在就更新,不存在就插入
9i已经支持了,但是只支持select子查询,
如果是单条数据记录,可以写作select …… from dual的子查询。但是merge不允许更新on条件里面的列的值,否则会报ORA-38104错误。 
语法为:
merge into table
using data_source
on (condition)
when matched then update_clause
when not matched then insert_clause;

merge into bonuses d
   using (select employee_id, salary, department_id from employees
   where department_id = 80) s
   on (d.employee_id = s.employee_id)
   when matched then update set d.bonus = d.bonus + s.salary*.01
     delete where (s.salary > 8000)
   when not matched then insert (d.employee_id, d.bonus)
     values (s.employee_id, s.salary*0.1)
     where (s.salary <= 8000);

============================

例子1:

merge into c1 a
  using c2 b  on (a.name = b.name and  a.areaid = b.areaid)
  when matched then
    update set a.id= seq_c1.nextval  --不用写where a.name = b.name and a.areaid = b.areaid
  when not matched then
    insert
      (id,name,areaid,)
    values
      (a.id, a.name,a.areaid);

例子2:

  merge into hfee a
      using dual b
      on (a.username = vcr_id.username and a.starttime = vcr_id.starttime)
      when matched then
        update
           set orginfee   = vcr_id.orginfee,
               favorfee   = vcr_id.favorfee,
               fee        = vcr_id.fee,
               balancefee = vi_balancefee
      when not matched then
        insert
          (username, starttime, orginfee, favorfee, fee, balancefee)
        values
          (vcr_id.username,
           vcr_id.starttime,
           nvl(vcr_id.orginfee, 0),
           nvl(vcr_id.favorfee, 0),
           nvl(vcr_id.fee, 0),
           nvl(vi_balancefee, 0));

merge into 出现错误 ora-30926,如何解决?

这个错误是由于using子句后的表存在多条符合条件的数据,可以用distinct、group by 等做处理:

merge into tdest d
using (select srckey, sum(srcdata) sumsrc from tsrc group by srckey) s
on (d.destkey = s.srckey)
when matched then
  update set d.destdata = s.sumsrc + d.destdata
when not matched then
  insert (destkey, destdata) values (srckey, sumsrc);

 merge into account a
using (select id, sum(balance) sum_balance from transaction group by id) t
on (a.id = t.id)
when matched then
  update set a.balance = a.balance + t.sum_balance
when not matched then
  insert (a.id, a.balance) values (t.id, t.sum_balance);


TAG:

 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

日历

« 2008-10-16  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 759
  • 日志数: 19
  • 建立时间: 2008-05-09
  • 更新时间: 2008-10-07

RSS订阅

Open Toolbar