且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我的自动递增 ID 会跳过 SQL Server 中的数字?

更新时间:2023-02-20 07:45:00

这是什么原因造成的?

What is causing this?

想到几个潜在的原因:

  • 行被删除了吗?
  • 您查看的结果不是按 id 排序的?
  • 在未提交的事务中分配了标识符?
  • 数据库引擎分配了潜在的标识符作为内部性能调整,但分配丢失了(例如,服务器意外重启)?

可能还有更多我没有想到的潜在原因.

There could be more potential causes I'm not thinking of.

我将来如何防止这种情况发生?

How can I prevent this in the future?

取决于原因.但这确实是一个有争议的问题.为什么需要防止这种情况发生"?这种情况究竟有什么问题?标识符不需要是连续的,它们只需要是唯一的.(***是顺序的索引,否则数据库将不得不重新建立索引.)

Depends on the cause. But it's kind of a moot point, really. Why would you need to "prevent this"? What exactly is wrong with this situation? Identifiers don't need to be consecutive, they just need to be unique. (And preferably sequential for an index, otherwise the database will have to re-build the index.)

我怎样才能阻止我当前的桌子继续走这条黑暗的道路?

How can I stop my current table from continuing on this dark road?

……生成唯一标识符的黑暗之路?好吧,我想您可以手动提供唯一标识符.GUID 非常适合这类事情.不过,有利也有弊.(我不知道最近的实现是否改善了这一点,但从历史上看,GUID 并不能成为一个好的聚集索引.)

The dark road of... generating unique identifiers? Well, I guess you could manually supply unique identifiers. GUIDs are good for that sort of thing. There are pros and cons, though. (I don't know if recent implementations have improved this, but historically GUIDs don't make for a good clustered index.)