问题描述: 有两个表,表1和表2 
表1里面有2条记录,表2里有10条记录,我现在想把表2里的数据更新到表1里去。如果表1里有同样的数据就更新,如果没有就新添加怎么写sql语句呀

解决方案 »

  1.   

    方法1:
    第一步:
    update 表1
    set 表1字段=表2字段
    from 表1 inner join 表2 on 表1主键=表2主键
    第二步:
    insert into表1
    select * from 表2 where not exists(select 1 from 表1 where 表1主键=表2主键)
      

  2.   

    方法2:用2008的merge,不过有点难懂。你如果是2008,去查查联机丛书吧
      

  3.   


    第一步少敲几个字吧
    update 表1
    set 表1字段=表2字段
    from 表2 where 表1主键=表2主键
      

  4.   

    merge into  tb1 as a
    using tb2 as b
    on a.主键=b.主键
    when matched
    then update set a.字段=b.字段
    when not matched
    then insert values(b.主键,b.字段)