SQL Server - 是否可以在行更新之前返回现有列值?

时间:2012-12-21 20:23:17

标签: sql sql-server sql-server-2008

我正在编写一个查询,用于更新论坛帖子( ForumPosts )的用户投票( ForumVotes )。用户可以向上或向下投票(投票将等于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
)

更新用户投票的简单查询

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

是否可以修改此查询以在更新前返回旧分数?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:7)

如果是 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 

答案 2 :(得分:3)

我通过向您显示不需要中间@previous表来扩展@ HLGEM的答案,您可以依赖OUTPUT直接返回数据而无需任何变量,只有别名:

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

如果直接运行此操作,您将获得一个包含1行数据和2列的表格:NewScoreOldSCore

相关问题