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

栏目: 数据库 · SQL Server · 发布时间: 7年前

内容简介:翻译自:https://stackoverflow.com/questions/13996748/sql-server-is-it-possible-to-return-an-existing-column-value-before-a-row-upda

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

翻译自:https://stackoverflow.com/questions/13996748/sql-server-is-it-possible-to-return-an-existing-column-value-before-a-row-upda


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

Tagging

Tagging

Gene Smith / New Riders / 2007-12-27 / GBP 28.99

Tagging is fast becoming one of the primary ways people organize and manage digital information. Tagging complements traditional organizational tools like folders and search on users desktops as well ......一起来看看 《Tagging》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具