例如:现有表table1,字段id,name,address,其中id为主键
插入语句insert into table1(id,name,address)values("01001","影子","河北")
如何在插入时进行判断table1中是否存在01001的记录,若不存在则插入,若存在则更新01001的name和address内容
在网上查了一下,表间更新时用merge into就可以,像我上面的情况有没有办法实现呢?

解决方案 »

  1.   


    --测试数据
    create table table1(id varchar2(100),name varchar2(1000),address varchar2(1000));
    insert into table1(id,name,address)values('01001','影子','河北') ;
    commit;--插入
    merge into table1 t1
    using (select '01002' id,'影子' name,'河北' address from dual) t2
    on (t1.id = t2.id)
    when matched then
         update set t1.name = t2.name, t1.address = t2.address
    when not matched then
         insert values (t2.id, t2.name,t2.address);
    commit;--查询结果
    select * from table1
    01001 影子 河北
    01002 影子2 辽宁--更新
    merge into table1 t1
    using (select '01001' id,'不是影子' name,'山西' address from dual) t2
    on (t1.id = t2.id)
    when matched then
         update set t1.name = t2.name, t1.address = t2.address
    when not matched then
         insert values (t2.id, t2.name,t2.address);
    commit;
    --查询结果
    select * from table101001 不是影子 山西
    01002 影子2 辽宁--删除测试数据
    drop table table1;
      

  2.   

    merge 是 用于两张表间的操作,你的insert的数据是从另张表来的吗?
      

  3.   

    using (select '01001' id,'不是影子' name,'山西' address from dual) t2
    将数据虚拟成表不就行了
      

  4.   

    delete from ... ;
    insert into ... ;
      

  5.   

    加个exception就可以了,因为你的ID是主健,所以如果已经存在相同的ID就会触发dup_val_on_idx,捕捉这个异常更新就好了.  begin
        insert into Table (ID,Value,..) values(1001,'222',...); 
        commit; 
      exception 
        when dup_val_on_idx then 
          update Table set value = '222' where id = 1001;
          commit;
        when others then
          Rollback;
      end;
      

  6.   

    主要是看LZ数据从何而来。
    如果不能批处理,像上面几位写的用merge into或者用过程都不太好弄。
      

  7.   

    也可以先用count判断是否存在该条记录,如果>0存在udpate,否则insert
      

  8.   

    用merge或过程来实现,前面几位说的很详细了:)