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

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

内容简介:翻译自: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


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

查看所有标签

猜你喜欢:

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

Types and Programming Languages

Types and Programming Languages

Benjamin C. Pierce / The MIT Press / 2002-2-1 / USD 95.00

A type system is a syntactic method for automatically checking the absence of certain erroneous behaviors by classifying program phrases according to the kinds of values they compute. The study of typ......一起来看看 《Types and Programming Languages》 这本书的介绍吧!

html转js在线工具
html转js在线工具

html转js在线工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具