Question

I have a table with 56 rows. Adding new rows starts from ID 59.

What can I do to continue with ID 57?

Était-ce utile?

La solution

This happens when you delete a column from the table or change the identity to be higher number.

It is possible to reset the identity, but unless you have a very good reason to do that (good reason may be deleting most of the table contents), I won't recommend doing that.

Some details of how to reseed the identity can be found here:

And the way to use it is

DBCC CHECKIDENT ( table_name, RESEED, new_reseed_value )

where new_reseed_value will be 57 for this specific case (i.e. the identity will start from 57). However, note that if there is something in the table with ID higher than 57, it will fail.

Alternatively, you can use:

SET IDENTITY_INSERT Table_Name ON
INSERT INTO Table_Name(ID, Other_Columns,You_Are_Inserting,You_Must_Specify_All_Of_Them)
VALUES (57, 'SomeData','OtherData',...)
SET IDENTITY_INSERT Table_Name OFF

This will allow you inserting by specifying the identity column value specifically without reseeding. Also, don't insert higher values than your current identity or you'll get failures on insertion.

Autres conseils

This is expected behaviour of IDENTITY columns. If you want consecutive numbers, you shouldn't be using them, because the identity value will increase every time you insert a new row, but will not decrease if you delete the last row, nor will it decrease if you begin a transaction, insert a new row, and then roll back the transaction.

You can use the DBCC CHECKIDENT command to change the identity value, but really, you should just change the column to a regular non-identity column and manage the value from your own code.

You need to turn on Identity_insert for specific table.

SET IDENTITY_INSERT YourTableName ON

Insert into YourTableName (IDField,rest of the column names)
values (57, rest of the column values)

SET IDENTITY_INSERT YourTableNAme OFF
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top