你的tb表必须要有主键,不能只好用游标。 
create table ta(a varchar(10),b varchar(10),c varchar(10),m int)
insert ta select 'J1','A1','A2',12
union select'J2','A1','A2',10
create table tb(a varchar(10),b varchar(10),d varchar(10),n int,t int)
insert tb select'J1','A1','B1',5,1
union all select'J1','A1','B2',12,1
union all select'J1','A1','B2',10,1
union all select'J2','A1','B1',5,1
union all select'J2','A1','B2',7,1
union all select'J2','A1','B1',5,1
union all select'J1','A2','B1',3,1
union all select'J1','A2','B2',5,1
union all select'J3','A2','B1',3,1
union all select'J3','A2','B2',5,1--看看有哪些要减的
select identity(int,1,1) id,*,0 zs into # from tb a where exists(select 1 from ta where a.a = a and a.b=b)
update z set zs = b.zs from # z,(
select id,isnull((select sum(n) from # where a.a=a and a.b = b and  a.id>id),0) as zs from # a 
) b where z.id = b.id
update a set zs =  zs - b.m from # a,ta b where a.a = b.a and a.b = b.b
delete # where zs >=0
update # set zs = 0 - n where n+zs <0
--更新要减的
update tb set n = a.n+b.zs from tb a,# b
   where a.a = b.a and a.b = b.b and a.d = b.d and a.n = b.n and a.t = b.t
--看看那些要加的
update # set b = b.c from # a,ta b where a.a = b.a and a.b = b.b
--补齐没有的
insert tb select a,b,d,0,1 from # a where not exists(select 1 from tb where a.a = a and a.b = b and a.d = d)
--更新要加的
update tb set n = a.n-b.zs from tb a,# b where a.a = b.a and a.b = b.b and a.d = b.d 
--更新状态
update tb set t = 0 where n = 0
select * from tb
/*
a          b          d          n           t           
---------- ---------- ---------- ----------- ----------- 
J1         A1         B1         0           0
J1         A1         B2         5           1
J1         A1         B2         10          1
J2         A1         B1         0           0
J2         A1         B2         2           1
J2         A1         B1         0           0
J1         A2         B1         8           1
J1         A2         B2         12          1
J3         A2         B1         3           1
J3         A2         B2         5           1
J2         A2         B1         5           1
J2         A2         B2         5           1
*/
drop table ta,tb,#