如何在 SQL 中将整数列值加 1
例如,假设列 ID
的值为 1,2,3,4, ...
现在,当我更新
此表时,ID
列应该增加 1,
现在 ID
将变为 2,3,4,5, ...
如何在 UPDATE
上将列的值增加 1?
For example, suppose a column ID
has values 1,2,3,4, ...
Now when I update
this table, the ID
column should increment by 1,
Now ID
will become 2,3,4,5, ...
How do you increment a column's value by 1 on UPDATE
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
要为表中的每个值添加 1...
要创建新值(通常比前一个最高值多一个),请使用 带有 IDENTITY 的列
To add one to every value in the table...
To create a new value, one more then the previous highest (usually), use a column with IDENTITY
如果您希望自动生成每行的唯一编号,根据尼尔的回答,这就是 IDENTITY。
如果每次更新表时您想要增加值(即它们不是键):
If you want to have an unique number for each row automatically generated, this is IDENTITY as per Neil's answer.
If each time you update the table you want to increase the values (ie they are not keys):
试试这个:
Try this:
对已接受答案的更新
可能会更短,像这样。
Update on the accepted answer
Might be shorter having it like this.
对于 postgresSQL
For postgresSQL
您可以使用
IDENTITY
来执行此操作为你。当您插入第一条记录时,您将获得
Id
1。You can use
IDENTITY
which will do this for you.When you insert your first record, you'll get an
Id
of 1.您可以尝试以下操作:
You could try the following:
在 Oracle 中,代码有点棘手。
您必须使用序列对象创建一个自动增量字段(该对象生成一个数字序列)。
使用以下 CREATE SEQUENCE 语法:
上面的代码创建一个名为 seq_person 的序列对象,该对象从 1 开始,并以 1 递增。它还将缓存最多 10 个值以提高性能。缓存选项指定内存中将存储多少序列值以加快访问速度。
要将新记录插入到“Persons”表中,我们必须使用 nextval 函数(该函数从 seq_person 序列中检索下一个值):
上面的 SQL 语句将向“Persons”表中插入一条新记录。 “ID”列将被分配 seq_person 序列中的下一个数字。 “FirstName”列将设置为“Lars”,“LastName”列将设置为“Monsen”。
In Oracle the code is a little bit more tricky.
You will have to create an auto-increment field with the sequence object (this object generates a number sequence).
Use the following CREATE SEQUENCE syntax:
The code above creates a sequence object called seq_person, that starts with 1 and will increment by 1. It will also cache up to 10 values for performance. The cache option specifies how many sequence values will be stored in memory for faster access.
To insert a new record into the "Persons" table, we will have to use the nextval function (this function retrieves the next value from seq_person sequence):
The SQL statement above would insert a new record into the "Persons" table. The "ID" column would be assigned the next number from the seq_person sequence. The "FirstName" column would be set to "Lars" and the "LastName" column would be set to "Monsen".