Question

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.

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.

Does anyone know why this happens? Or how this problem can be bypassed?

Kind regards, Tom

Was it helpful?

Solution

As per MSDN:

Current identity value is set to the 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. Otherwise, the next row inserted uses new_reseed_value + the current increment 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.

OTHER TIPS

In addtion to Luaan's answer, you can bypass it by using

 set identity_insert [tablename] on 

and manually setting the identity value via an insert statement

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top