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

批量更新
表A
id Bcount 
1 null
2 null
3 null
表B
id Aid
1 2
2 1
3 1

Aid为表A的id,
现在要更新表A的Bcount字段,结果如下:
表A
id Bcount
1 2
2 1
3 null

------解决方案--------------------
SQL code


create table a (id int identity,bcount int)
create table b (id int identity,aid int)
insert a select null union all select null union all select null
insert b select 2 union all select 1 union all select 1


select * from a 
/*
id    bcount
1    NULL
2    NULL
3    NULL
*/
select * from b
/*
id    aid
1    2
2    1
3    1
*/
update a set bcount=(select count(1) from b where a.id=b.aid group by b.aid)

/*
id    bcount
1    2
2    1
3    NULL
*/

drop table a
drop table b