I need to change the primary key of a table to an identity column, and there\'s already a number of rows in table.
I\'ve got a script to clean up the IDs to ensure
Simple explanation
Rename the existing column using sp_RENAME
EXEC sp_RENAME 'Table_Name.Existing_ColumnName' , 'New_ColumnName', 'COLUMN'
Example for Rename :
The existing column UserID is renamed as OldUserID
EXEC sp_RENAME 'AdminUsers.UserID' , 'OldUserID', 'COLUMN'
Then add a new column using alter query to set as primary key and identity value
ALTER TABLE TableName ADD Old_ColumnName INT NOT NULL PRIMARY KEY IDENTITY(1,1)
Example for Set Primary key
The new created column name is UserID
ALTER TABLE Users ADD UserID INT NOT NULL PRIMARY KEY IDENTITY(1,1)
then Drop the Renamed Column
ALTER TABLE Table_Name DROP COLUMN Renamed_ColumnName
Example for Drop renamed column
ALTER TABLE Users DROP COLUMN OldUserID
Now we've adding a primarykey and identity to the existing column on the table.