高分在线,如果用存储过程实现查询后再更新的功能,详情见帖

asilas 2004-04-09 09:01:51
我这里有两个表,
[A]
ID int(自动编号)
UserID int
PostID int
result int

[b]
userID
point

我现在想用一个存储过程实现下面的功能
从A表里查询postid=某个数值的记录,
然后把这些记录的result加到[b]表对应的相同的USERID的point中

在线等待,解决就给分




...全文
41 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
asilas 2004-04-09
  • 打赏
  • 举报
回复
结帖,谢谢
zjcxc 元老 2004-04-09
  • 打赏
  • 举报
回复

--写成处理的存储过程
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

zjcxc 元老 2004-04-09
  • 打赏
  • 举报
回复
--上面错了,忘了加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
zjcxc 元老 2004-04-09
  • 打赏
  • 举报
回复
如果我要处理的不止是一个result,这个方法也行吗?


当然没问题.
zjcxc 元老 2004-04-09
  • 打赏
  • 举报
回复
--如果只需要更新已经有的userid,则去掉插入的语句部分
asilas 2004-04-09
  • 打赏
  • 举报
回复
如果我要处理的不止是一个result,这个方法也行吗?
zjcxc 元老 2004-04-09
  • 打赏
  • 举报
回复

--写成处理的存储过程
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
zjcxc 元老 2004-04-09
  • 打赏
  • 举报
回复

--更新已经有的
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

34,576

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧