简体   繁体   English

身分有时为SEED,有时为SEED +1

[英]Identity sometimes SEED, sometimes SEED +1

We do intigration testing on a test database which has pre-filled data. 我们对具有预填充数据的测试数据库进行引诱测试。 Sometimes however, for specific tests, we want to add extra data. 但是,有时对于特定的测试,我们想添加额外的数据。 To not mess with the existing data (unless intentional) we want to start the extra entries with ID 300001. 为了不弄乱现有数据(除非是有意的),我们希望以ID 300001开始额外的条目。

USE DB

EXEC sp_MSForEachTable @command1 = 

'IF OBJECTPROPERTY(object_id(''?''), ''TableHasIdentity'') = 1
BEGIN
 DBCC CHECKIDENT (''?'', RESEED, 300000);
 DBCC CHECKIDENT (''?'', RESEED, 300000);
END'
GO

However, after inserting new entries after this has happend, some tables hand out ID 300000, some hand out 300001 which makes testing it a bit harder. 但是,在发生这种情况后插入新条目之后,某些表将分发ID 300000,一些表将分发300001,这使测试变得更加困难。

Does anyone know why this happens? 有谁知道为什么会这样吗? Or how this problem can be bypassed? 还是可以绕开这个问题?

Kind regards, Tom 亲切的问候,汤姆

As per MSDN: 根据MSDN:

Current identity value is set to the new_reseed_value. 当前身份值设置为new_reseed_value。 If no rows have been inserted into the table since the table was created, or if all rows have been removed by using the TRUNCATE TABLE statement, the first row inserted after you run DBCC CHECKIDENT uses new_reseed_value as the identity. 如果自创建表以来未将任何行插入表中,或者使用TRUNCATE TABLE语句删除了所有行,则在运行DBCC CHECKIDENT之后插入的第一行将使用new_reseed_value作为标识。 Otherwise, the next row inserted uses new_reseed_value + the current increment value. 否则,插入的下一行将使用new_reseed_value +当前增量值。

So if you want consistent behaviour, insert and delete a single row to / from each of the tables before reseeding. 因此,如果要保持一致的行为,请在重新播种之前从每个表中插入一行或从其中删除一行。

However, I'd like to point out that you're not supposed to rely on identity columns having any sort of pattern. 但是,我想指出的是,您不应该依赖具有任何模式的身份列。 While in practice identity behaves some way, it doesn't guarantee it. 尽管在实践中身份会表现某种方式,但并不能保证一定能做到。 A typical scenario being transaction A that creates a few new rows, transaction B creating a few more, and then rolling the transaction A back and committing B yields a gap. 一个典型的场景是事务A创建一些新行,事务B创建更多行,然后回滚事务A并提交B会产生间隙。

In addtion to Luaan's answer, you can bypass it by using 除了Luaan的答案外,您还可以使用

 set identity_insert [tablename] on 

and manually setting the identity value via an insert statement 并通过insert语句手动设置标识值

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

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