删除行后重用标识值

发布于 2024-10-05 00:53:28 字数 210 浏览 0 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

尘曦 2024-10-12 00:53:28

您可以使用以下命令来设置 IDENTITY 值:

DBCC CHECKIDENT (orders, RESEED, 999)

这意味着您必须根据每个 DELETE 运行该语句。这应该开始强调为什么这是一个坏主意......

数据库不关心顺序值 - 这仅用于演示。

You can use the following to set the IDENTITY value:

DBCC CHECKIDENT (orders, RESEED, 999)

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.

不一样的天空 2024-10-12 00:53:28

如果您想在删除所有行后重置标识,请执行以下操作之一

--instead of delete, resets identity value
TRUNCATE TABLE orders

--or if TRUNCATE fails because of FKs, use this after DELETE
DBCC CHECKIDENT (orders, RESEED, 1)

否则,内部值无论是否有间隙都应该无关紧要。

If you want to reset the identity after deleting all rows then do one of these

--instead of delete, resets identity value
TRUNCATE TABLE orders

--or if TRUNCATE fails because of FKs, use this after DELETE
DBCC CHECKIDENT (orders, RESEED, 1)

Otherwise, the internal value should not matter whether gaps or not.

内心旳酸楚 2024-10-12 00:53:28

默认情况下,identity 字段不会重用旧值。您可以使用 dbcc checkident 重新播种它们,但不建议这样做,因为如果您重新设定种子值低于表中仍然存在的值,您将遇到关键违规。一般来说,您不应该关心 PK 值是多少。它们不连续的事实不会造成任何伤害。

identity fields do not reuse old values by default. You can reseed them with dbcc 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文