Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Reset Identity ID in already populated table

hey all. I have a table in my DB that has about a thousand records in it. I would like to reset the identity column so that all of the ID's are sequential again. I was looking at this but I'm ASSuming that it only works on an empty table

Current Table

ID    |    Name
1           Joe
2           Phil
5           Jan
88          Rob

Desired Table

ID    |    Name
1           Joe
2           Phil
3           Jan
4           Rob

Thanks in advance

like image 465
Chase Florell Avatar asked May 08 '10 00:05

Chase Florell


People also ask

How do I change the identity in an existing column in SQL Server?

You can't alter the existing columns for identity. You have 2 options, Create a new table with identity & drop the existing table. Create a new column with identity & drop the existing column.

How do you update the identity column in a table?

You cannot update the value of the identity column in SQL Server using UPDATE statement. You can delete the existing column and re-insert it with a new identity value. The only way to remove the identity property for the column is by removing the identity column itself.


1 Answers

The easiest way would be to make a copy of the current table, fix up any parentid issues, drop it and then rename the new one.

You could also temporarily remove the IDENTITY and try the folowing:

;WITH TBL AS
(
  SELECT *, ROW_NUMBER(ORDER BY ID) AS RN
  FROM CURRENT_TABLE
)
UPDATE TBL
SET ID = RN

Or, if you don't care about the order of the records, this

DECLARE INT @id;
SET @id = 0;

UPDATE CURRENT_TABLE
SET @id = ID = @id + 1;
like image 181
Chris Bednarski Avatar answered Sep 22 '22 07:09

Chris Bednarski