表A  tblA
     f1   fNumber
     100   900
     101   200
     102   300表B  tblB
     f1   fNumber
     100   300
     101   20
     130   500先从表B(tblB)中查询,如果f1的值在表A中存在,则将表A(tblA)中fNumber的值相加,如果不存在,则在表A中插入新的值,得到的结果如下:    f1   fNumber
    100   1200
    101   220
    102   300
    130   500

解决方案 »

  1.   


    create table tblA(f1 int , fNumber int)
    insert tblA
    select 100,900
    union all
    select 101,200
    union all
    select 102,300create table tblB(f1 int,  fNumber int)
    insert tblB
    select 100,300
    union all
    select 101,20
    union all
    select 130,500
    select f1,sum(fNumber) fNumber from 
    ( select * from tblA
    union all 
    select * from tblB  ) a
    group by f1
      

  2.   

    update tblA set fNumber=A.fNumber+B.fNumber from tblA A,tblB B where A.f1=B.f1insert into tblA select * from tblB where not exists(select 1 from tblA where f1=tblB.f1)
      

  3.   

    --更新tblA,将tblB中f1相同的fNumber值累加到tblA中对应记录
    update A set fNumber=A.fNumber+B.fNumber from tblA A,tblB B where A.f1=B.f1--将tblB在tblA中不存在的f1所对应记录新增到tblA
    insert into tblA select * from tblB where not exists(select 1 from tblA where f1=tblB.f1)
      

  4.   

    --如果要查詢
    select f1  ,sum(fNumber) as fNumber
    from 
      (select f1,fNumber from A
       union all
       seect f1,fNumber from B) T
    group by f1--如果要更新A表
    update A
    set A.fNumber=A.fNumber+B.fNumber
    from A inner join B on A.f1=B.f1
    insert into A(f1,fNumber)
    select f1,fNumber from B where not exists(select 1 from A  where f1=B.f1) 
      

  5.   

    When a man~~ love a woman!