Click here to Skip to main content
15,886,033 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello to everyone
There is a part of code using T-sql, quite simple and it does not need some extra explanations.
SQL
select * from MyTable
delete   from MyTable where id =  2

Just one simple question. I am a newer is the DB sphere... How can a primary key be recounted automatically if it is of integer type?
Sorry for such a simple question.
Posted
Comments
Jörgen Andersson 21-Aug-15 7:56am    
Why do you want to recalculate the IDs?
A surrogate key does not need to be recalculated and shouldn't be recalculated.
Gaps in a sequence does not affect the database the slightest.
The only reason I can see is if you want to feed your OCD.
PIEBALDconsult 21-Aug-15 16:47pm    
Yeah, don't do that. You must be doing something wrong.
In fact, try not to delete, use something like an IsDeleted flag.

You have at least three options:
- you can use IDENTITY[^]
- use uniqueidentifier along with NEWID[^]
- or use a SEQUENCE[^]

Personally I'd prefer NEWID over IDENTITY especially if the keys need to be unique across different databases.
 
Share this answer
 
v2
Comments
PIEBALDconsult 21-Aug-15 16:50pm    
I can't stand IDENTITY, but I also know that I'm in the minority. For integer IDs I'd definitely use a SEQUENCE, but I prefer GUIDs.
Wendelius 22-Aug-15 2:35am    
IMHO identity works with small, isolated databases but I share your opinion, identities are not so good as other options.
Hi Dzianis,

As per my understanding of your question, you want to recalculate/ reset identity value of the column, not the primary key itself.

If I am correct then please use below DBCC command. That will help you to reset the identity value of the column.

SQL
DBCC CHECKIDENT('[table_name]', RESEED, [new_reseed_value])


So, in your case you can put something like below"

SQL
DBCC CHECKIDENT('MyTable', RESEED, 1)


Above query will reset your identity column to value 1. So from the next value 2 will be inserted for the column id.

Please let me know if you have any concern or query on this.

Thanks
 
Share this answer
 
My answer is Don't do it.
Why ?
Simply because there is no downside to have a hole in primary key values, and renumbering the key offer no gain (of space or speed).

But renumbering the key have a downside, you have to shutdown all access to the base while you are renumbering it.
 
Share this answer
 
v2

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