簡體   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