日期:2014-05-18  浏览次数:20502 次

知识是无价的,所以我给最高分!(两表条件插入?)
我现在有A表和B表,如下:

                A表
  hh               pm           sl
10000         XXXX         60
10001         XXXX         10
10025         XXXX         50
35685         XXXX         20
20523         XXXX         20
12584         XXXX         1000
58954         XXXX         500
52148         XXXX         2000
                 
                  B表                                                  
  hh               pm           sl
10001         XXXX         100
20523         XXXX         120
12584         XXXX         2000
58954         XXXX         600
52148         XXXX         3000

我现想把A表中的数据插入到B表中,B表没有的数据进行插入,B表中有的只将 'sl '累计,要求效果如下:

                    B表
     
  hh               pm           sl
10000         XXXX         60
10001         XXXX         110
10025         XXXX         50
35685         XXXX         20
20523         XXXX         140
12584         XXXX         3000
58954         XXXX         1100
52148         XXXX         5000

------解决方案--------------------
--追加B中不存在的
insert into B(hh,pm,sl)
select A.hh,A.pm,A.sl
from A left join B on A.hh=B.hh
where B.hh is null


--更新存在的
update B set sl=isnull(sl,0) + isnull(A.sl,0)
from A inner join B on A.hh=B.hh

------解决方案--------------------


先更新再插入
update B
set sl=isnull(sl,0) + sum(isnull(A.sl,0))--如果A存在一对多关系时sum
from A inner join B on A.hh=B.hh

insert into B
select *
from
A where not exists(select 1 from b where A.hh=B.hh)