Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
After i delete a row and then insert a new row the auto increment row wont assign the correct next number. example if i have

1 last first
2 last first
3 last first

after delete

1 last first
2 last first

after insert

1 last first
2 last first
4 last first

I need some help fixing this, any help would be great thanks.
Posted

[Adding to John's response]

If you want to understand why, think of what happens if you had this:

1 last first
2 last first
3 last first


And then you deleted the 2nd row to get this:

1 last first
3 last first


Now when you do an insert what would you want the index to be? 3 would certainly be wrong (since it already exists). Do you want it to go find that 2 is missing and thus use 2? What if there are multiple such deleted rows?
 
Share this answer
 
v2
Comments
ajep 31-Oct-10 20:48pm    
Thanks for the help, but i made that column edible because it was an identity with auto+
so i did this with help
INSERT INTO table1 (ID, .....) VALUES ((SELECT MAX(ID) + 1 FROM table1), .....)
AspDotNetDev 31-Oct-10 22:58pm    
Ajep, that may get you into trouble if you have more than one of those commands hitting the database at once. You could end up with 2 (or more) rows that have the same value.
It's not broken and you shouldn't try to "fix" it. SQL Server maintains the index of the last inserted item. It's supposed to be a unique value, and the only way that can be guaranteed is if you allow SQL Server to maintain that index. You *can* reset the value, but you'd have to reset it again when you've filled the "missing" index.

Take my word for it, you're worried about nothing.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900