7

我正在编写一个查询来更新用户对论坛帖子(ForumPosts )的投票( ForumVotes 。用户可以投票赞成或反对(投票将等于 1 或 -1)。此问题专门针对更改用户的投票,因此ForumVotes表中已存在投票记录。

ForumPosts表存储每个帖子的总分,因此我需要保持该字段同步。要重新计算总分,我需要先减去旧票,然后再添加新票,因此我需要在更新用户投票记录之前获取旧票。

我知道我可以用 2 个查询来做到这一点,但我想知道是否有可能(在 SQL Server 2008 中)更新在执行更新之前返回列的值?

这是一个例子:

TABLE ForumPosts (
    postID bigint,
    score int,
    ... etc
)

-- existing vote is in this table:

TABLE ForumVotes (
    postFK bigint,
    userFK bigint,
    score int
)

更新用户投票的简单查询

UPDATE ForumVotes 
SET score = @newVote 
WHERE postFK = @postID
AND userFK = @userID

可以修改此查询以返回更新前的旧分数吗?

4

3 回答 3

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
于 2012-12-21T20:28:05.743 回答
8

如果是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 
于 2012-12-21T20:38:07.333 回答
3

I'll expand upon @HLGEM's answer by showing you don't need an intermediate @previous table, you can rely on OUTPUT returning data directly without any variables, only aliasing:

UPDATE
    ForumVotes
SET
    Score = @newVote
OUTPUT
    INSERTED.Score AS NewScore,
    DELETED.Score  AS OldScore
WHERE
    PostFK = @postId AND
    USerFK = @userId

If you run this directly, you'll get a table returned with 1 row of data and 2 columns: NewScore and OldSCore.

于 2016-04-27T04:26:33.137 回答