--更新已经有的
update b set point=isnull(b.point,0)+isnull(a.result,0)
from b join(
select userid,result from A表 
where postid=某个数值
group by result
)a on a.userid=b.userid--插入不存在的
insert b(userid,point)
select a.*
from(
select userid,result from A表 
where postid=某个数值
group by result
)a left join b on a.userid=b.userid
where b.userid is null

解决方案 »

  1.   


    --写成处理的存储过程
    create proc p_process
    @PostID int
    as
    set xact_abort on
    begin tran --用事务处理
    --更新已经有的
    update b set point=isnull(b.point,0)+isnull(a.result,0)
    from b join(
    select userid,result from A表 
    where postid=@PostID
    group by result
    )a on a.userid=b.userid

    --插入不存在的
    insert b(userid,point)
    select a.*
    from(
    select userid,result from A表 
    where postid=@PostID
    group by result
    )a left join b on a.userid=b.userid
    where b.userid is null
    commit tran
    go
      

  2.   

    如果我要处理的不止是一个result,这个方法也行吗?
      

  3.   

    --如果只需要更新已经有的userid,则去掉插入的语句部分
      

  4.   

    如果我要处理的不止是一个result,这个方法也行吗?
    当然没问题.
      

  5.   

    --上面错了,忘了加sum,改一下--更新已经有的
    update b set point=isnull(b.point,0)+isnull(a.result,0)
    from b join(
    select userid,,result=sum(result) from A表 
    where postid=某个数值
    group by result
    )a on a.userid=b.userid--插入不存在的
    insert b(userid,point)
    select a.*
    from(
    select userid,result=sum(result) from A表 
    where postid=某个数值
    group by result
    )a left join b on a.userid=b.userid
    where b.userid is null
      

  6.   


    --写成处理的存储过程
    create proc p_process
    @PostID int
    as
    set xact_abort on
    begin tran --用事务处理
    --更新已经有的
    update b set point=isnull(b.point,0)+isnull(a.result,0)
    from b join(
    select userid,result=sum(result) from A表 
    where postid=@PostID
    group by result
    )a on a.userid=b.userid

    --插入不存在的
    insert b(userid,point)
    select a.*
    from(
    select userid,result=sum(result) from A表 
    where postid=@PostID
    group by result
    )a left join b on a.userid=b.userid
    where b.userid is null
    commit tran
    go