Red*_*pia 7 sql sql-server sql-server-2008
我正在写一个查询,更新用户的投票(ForumVotes的一个论坛帖子()ForumPosts).用户可以向上或向下投票(投票将等于1或-1).此问题特定于更改用户的投票,因此ForumVotes表中已存在投票记录.
该ForumPosts表存储每个职位的总成绩,所以我需要保持同步这一领域.要重新计算总分,我需要在添加新投票之前先减去旧投票,因此我需要在更新用户的投票记录之前获得旧投票.
我知道我可以用2个查询来做这个,但我想知道是否有可能(在SQL Server 2008中)UPDATE在执行更新之前返回列的值?
这是一个例子:
TABLE ForumPosts (
postID bigint,
score int,
... etc
)
-- existing vote is in this table:
TABLE ForumVotes (
postFK bigint,
userFK bigint,
score int
)
Run Code Online (Sandbox Code Playgroud)
用于更新用户投票的简单查询
UPDATE ForumVotes
SET score = @newVote
WHERE postFK = @postID
AND userFK = @userID
Run Code Online (Sandbox Code Playgroud)
可以修改此查询以在更新之前返回旧分数吗?
HLG*_*GEM 13
尝试OUTPUT子句:
declare @previous table(newscore int, Oldscore int, postFK int, userFK int)
UPDATE ForumVotes
SET score = @newVote
OUTPUT inserted.score,deleted.score, deleted.postFK, deleted.userFK into @previous
WHERE postFK = @postID
AND userFK = @userID
select * from @previous
Run Code Online (Sandbox Code Playgroud)
如果是single row affected query (ie; update using key(s))
那么;
declare @oldVote varchar(50)
update ForumVotes
set score = @newVote, @oldVote = score
where postFK = @postId and userFK = @userId
--to receive the old value
select @oldVote
Run Code Online (Sandbox Code Playgroud)