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

请教一个SQL
有两个表A:ID,GZ
B:BM,GZ
我现在想要求修改A表中ID为5的记录的GZ字段,使其等于B表中所有BM= 'AAAA '的记录的GZ字段的和.
谢谢

------解决方案--------------------
有两个表A:ID,GZ
B:BM,GZ
我现在想要求修改A表中ID为5的记录的GZ字段,使其等于B表中所有BM= 'AAAA '的记录的GZ字段的和.
谢谢

方法1:
update 表A set GZ=(select sum(GZ) 表B where BM= 'AAAA ') where ID=5

方法2:
declare @GZ int
select @GZ = sum(GZ) from 表B where BM= 'AAAA '
update 表A set GZ=@GZ where ID=5
------解决方案--------------------
declare @length int

select @length=count(*) from b where bm= 'aaaa '

if @length != 0
update a set gz=(select sum(gz) from b where bm= 'aaaa ') where id=5
else
update a set gz=0 where id = 5