简体   繁体   English

IDENTITY SEED 基于其他表种子值递增

[英]IDENTITY SEED is incrementing based on other tables seed values

I'm using SQL SERVER 2017 and using SSMS 2018. I have created a few tables whose Primary Key is int and enabled Is Identity and set Identity Increment = 1 and Identity Seed=1 For all the tables I have used the same method.我正在使用 SQL SERVER 2017 和 SSMS 2018。我创建了一些主键为int并启用Is Identity的表,并设置Identity Increment = 1 和 Identity Seed=1对于我使用相同方法的所有表。 But When I added one record in a table say Lead it's ID was 2 , Then added value to the table say Followup then its ID was 3 .但是当我在表中添加一条记录时说Lead它的ID2 ,然后将值添加到表中说Followup然后它的ID3 Here I'm adding the screenshots for a better understanding在这里我添加屏幕截图以便更好地理解

Lead Table铅表铅表

Followup Table跟进表跟进表

Is there any option available to avoid this?有什么办法可以避免这种情况吗? can we keep the identity individual for each table?我们可以为每张桌子保留身份吗?

The documentation is quite specific about what identity does not guarantee :文档非常具体地说明了identity不能保证的内容:

The identity property on a column does not guarantee the following:列上的标识属性不保证以下内容:

  • Uniqueness of the value .值的唯一性 . . . .

  • Consecutive values within a transaction .事务中的连续值 . . . .

  • Consecutive values after server restart or other failures .服务器重新启动或其他故障后的连续值 . . . .

  • Reuse of values重用价值

In general, the "uniqueness" property is a non-issue, because identity columns are usually the primary key (or routinely declared at least unique ), which does guarantee uniqueness.一般来说,“唯一性”属性不是问题,因为标识列通常是主键(或通常至少声明为unique性),这确实保证了唯一性。

The purpose of an identity column is to provide a unique numeric identifier different from other rows, so it can be readily used as a primary key. identity列的目的是提供一个不同于其他行的唯一数字标识符,因此它可以很容易地用作主键。 There are no other guarantees.没有其他保证。 And for performance SQL Server has lots of short-cuts that result in gaps.并且为了性能 SQL 服务器有许多导致差距的捷径。

If you want no gaps, then the simplest way is to assign a value when querying:如果您不希望有任何间隙,那么最简单的方法是在查询时分配一个值:

row_number() over (order by <identity column>)

That is not 100% satisfying, because deletions can affect the value.这不是 100% 令人满意,因为删除会影响值。 I also think that on parallel systems, inserts can as well (because identities might be cached on individual nodes).我还认为在并行系统上,插入也可以(因为身份可能缓存在各个节点上)。

If you do not care about performance, you can use a sequence for assigning a value.如果您不关心性能,则可以使用sequence来分配值。 This is less performant than using an identity .这比使用identity的性能要差。 Basically, it requires serializing all the inserts to guarantee the properties of the insert.基本上,它需要序列化所有的插入来保证插入的属性。

I should note that even with a sequence, a failed insert can still produce gaps, so it still might not do what you want.我应该注意,即使有一个序列,失败的插入仍然会产生间隙,所以它仍然可能无法达到你想要的效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM