在 SQL Server 中增加整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1850393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Incrementing an Integer in SQL Server
提问by Ana Betts
Noob question here, every time I change a certain record in an SQL Server 2008 R2 table, I want to increment a RevisionId record; to do so, I'm using the following syntax:
菜鸟问题在这里,每次更改SQL Server 2008 R2表中的某条记录时,我都想增加一条RevisionId记录;为此,我使用以下语法:
UPDATE TheTable
SET RevisionId=(SELECT RevisionId
FROM TheTable
WHERE Id=@id) + 1
WHERE Id=@id;
Btw, I'm going to put this into a trigger so that this happens automagically, but while this code works, it feels pretty clunky—any cleaner way to do this?
顺便说一句,我将把它放到触发器中,这样这会自动发生,但是虽然这段代码有效,但感觉很笨重——有没有更简洁的方法来做到这一点?
回答by Mark Byers
You don't need the inner select:
您不需要内部选择:
UPDATE TheTable SET RevisionId = RevisionId + 1 WHERE Id=@id
回答by wallyk
This is a SQL idiom for incrementing a field:
这是用于增加字段的 SQL 习语:
UPDATE TheTable
SET RevisionId = RevisionId + 1
WHERE Id=@id;
回答by No Refunds No Returns
If you're just looking for a "row version" value, have you considered adding a TimeStamp column to your table? SQL Server updates it for you "automagically" every time. No code on your part at all. They just won't be sequentially numbered, if that's important to you.
如果您只是在寻找“行版本”值,您是否考虑过在表中添加一个 TimeStamp 列?SQL Server 每次都会“自动”为您更新它。您根本没有代码。如果这对您很重要,它们只是不会按顺序编号。