删除行后重用标识值
在 SQL Server 2008 Express 中删除行后是否可以重用标识字段值?这是一个例子。假设我有一个表,其中一个 Id 字段作为主键(身份)。如果我添加五行,我将有这 5 个 Id:1、2、3、4、5。如果我要删除这些行,然后再添加 5 行,新行将有 Id:6、7、8、 9, 10. 是否可以让其再次从 1 开始?
我是否必须从另一个表中删除数据才能完成此操作?感谢您的帮助。
Is it possible to reuse an identity field value after deleting rows in SQL Server 2008 Express? Here is an example. Suppose I have a table with an Id field as a primary key (identity). If I add five rows, I will have these 5 Ids: 1, 2, 3, 4, 5. If I were to delete these rows, and then add five more, the new rows would have Ids: 6, 7, 8, 9, 10. Is it possible to let it start over at 1 again?
Do I have to delete data from another table in order to accomplish this? Thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用以下命令来设置 IDENTITY 值:
这意味着您必须根据每个 DELETE 运行该语句。这应该开始强调为什么这是一个坏主意......
数据库不关心顺序值 - 这仅用于演示。
You can use the following to set the IDENTITY value:
That means you'll have to run the statement based on every DELETE. That should start to highlight why this is a bad idea...
The database doesn't care about sequential values - that's for presentation only.
如果您想在删除所有行后重置标识,请执行以下操作之一
否则,内部值无论是否有间隙都应该无关紧要。
If you want to reset the identity after deleting all rows then do one of these
Otherwise, the internal value should not matter whether gaps or not.
默认情况下,
identity
字段不会重用旧值。您可以使用dbcc checkident
重新播种它们,但不建议这样做,因为如果您重新设定种子值低于表中仍然存在的值,您将遇到关键违规。一般来说,您不应该关心 PK 值是多少。它们不连续的事实不会造成任何伤害。identity
fields do not reuse old values by default. You can reseed them withdbcc checkident
, but this isn't suggested as you will get key violations if you reseed below a value that still exists in the table. In general, you shouldn't care what the PK values are. The fact that they're not contiguous doesn't hurt anything.