Click here to Skip to main content
15,891,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello All,
I have deleted some date from my table like at id=25 and id=27. Now i Have data at id=28.Can you please tell me how to reset primary key from 1 to ...........so that old data will not delete and primary key will show from 1 to ..............

only to reset primary key and it will replace 25 and 27 with the other data
Posted
Updated 16-Dec-10 8:58am
v2
Comments
Abdul Quader Mamun 16-Dec-10 14:58pm    
Spelling check.

Thank you for your question.

Remove foreign key reference (if any) from YourTabe and set Is Identity to No in column properties windows in Microsoft SQL Server Management Studio. Execute the bellow SQL using Management Studio.

SQL
USE YourDataBase

SELECT [YourTableId],ROW_NUMBER() OVER (ORDER BY YourTableId ) AS RowNumber
    into #tempTable from [YourTable]

DECLARE your_table_cursor CURSOR FOR
    SELECT [YourTableId], RowNumber
    FROM #tempTable

OPEN your_table_cursor

DECLARE @YourTableId int
DECLARE @RowNumber int

FETCH NEXT FROM your_table_cursor
INTO @YourTableId, @RowNumber

WHILE @@FETCH_STATUS = 0
BEGIN
    UPDATE  [YourTable]
        SET [YourTableId] = @RowNumber
        WHERE [YourTableId] = @YourTableId

    FETCH NEXT FROM your_table_cursor
    INTO @YourTableId, @RowNumber
END


CLOSE your_table_cursor
DEALLOCATE your_table_cursor

DROP TABLE #tempTable


Set Is Identity to Yes and set Identity increment to 1 and Identity Seed to 1 in column properties windows in Management Studio. Then set reference.

Thanks,
Mamun
 
Share this answer
 
v6
Comments
amit2620 20-Dec-10 11:59am    
very good post .It works for me.Thanks
I think the first question you'll have to ask yorself is: Why???
 
Share this answer
 
Comments
amit2620 20-Dec-10 11:59am    
I think its time to ask it from your side
I think the easiest way is to copy the table (ie make a new table that is identical to your table, insert all the posts to the new table. That way you should get a nice Id order )

Another way is to turn the identity of , manually change the ids, and then
turn the id on again.

It should not matter much though that an ID column has holes in it.
 
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