This question already has answers here:
Adding an identity to an existing column (19 answers)
Closed 6 days ago.
I have an empty table that I thought was auto increment until I tried adding my first record. That's when SQL told me this:
Cannot insert the value NULL into column 'ID', table 'DB_9CF886_mcl959.dbo.Posts'; column does not allow nulls. INSERT fails.
So I tried to add the identity to it:
alter table dbo.Posts ADD ID INT IDENTITY(1,1) CONSTRAINT PK_Posts1 PRIMARY KEY CLUSTERED;
That gave me this error:
Column names in each table must be unique. Column name 'ID' in table 'dbo.Posts' is specified more than once.
I could drop the table and recreate it, but I'd like to know how to FIX IT to add the identity to the ID column.
Screenshot of database: dbo.Posts
2条答案
按热度按时间gmol16391#
While it's true that you cannot add
IDENTITY
to an existing column, and that addingIDENTITY
to an existing table means adding a new column - it's also true that you don't need to useIDENTITY
- nor do you need toDROP
anything either.Instead,
ALTER
your existingID
column to use aSEQUENCE
object for new values - which has (effectively) the same end-result asIDENTITY
- but this way it will preserve your existingID
column values, preserve foreign-key references, and preserve yourCLUSTERED
index without needing a table rebuild.Do this:
0s7z1bwu2#
Below is an example that uses
SWITCH
to move data into another table of identical schema that already has theIDENTITY
.