Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Adding an identity to an existing column

I want to modify the primary key of a table to an identity column, and there's previously a number of rows in the table.

I've got a script to clean up the IDs to ensure they're regular starting at 1, works fine on my test database.

What's the SQL command to alter the column to have an identity property?
by

2 Answers

espadacoder11
You cannot alter a column to be an IDENTITY column. What you'll need to do is create a new column which is defined as an IDENTITY from the get-go, then drop the old column, and rename the new one to the old name.

ALTER TABLE (yourTable) ADD NewColumn INT IDENTITY(1,1)

ALTER TABLE (yourTable) DROP COLUMN OldColumnName

EXEC sp_rename 'yourTable.NewColumn', 'OldColumnName', 'COLUMN'
kshitijrana14
Right click on table name in Object Explorer. You will get some options. Click on 'Design'. A new tab will be opened for this table. You can add Identity constraint here in 'Column Properties'.

Login / Signup to Answer the Question.