繁体   English   中英

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

[英]SQL Server - Is it possible to return an existing column value before a row update?

我正在写一个查询,对于一个论坛帖子(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

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

尝试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

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

我将通过展示你不需要一个中间的@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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM