Alter table column for primary key and identity

后端 未结 2 1119
甜味超标
甜味超标 2021-02-20 15:47

I have table created and want to alter that table. I want to add a primary key and identity(1,1).

I can apply primary key but applying identity gives error.

相关标签:
2条回答
  • 2021-02-20 16:01

    I found this because I was looking for the same answer to assign IDENTITY programmatically to a table in SQL Server 2019. My situation is that the table I was trying to apply this to was an imported table where the column that I was attempting to apply IDENTITY to had IDENTITY in the table where it was imported from so it met the requirements of IDENTITY - each value was unique and had the correct data type. This and other research helped me to understand I could not do this programmatically.

    But it does not prevent me from actually accomplishing the result. Instead of programmatically, I can open the table in design view in SSMS and assign IDENTITY there so long as seed and identity interval match the original setup of the table. Obviously, not as quick a solution if a lot of tables are involved but protects the integrity of IDENTITY values if they are used as Foreign Keys in other associated tables.

    0 讨论(0)
  • 2021-02-20 16:04

    You cannot alter the definition of an existing column in the database, to add the IDENTITY property (nor to remove it). You have to create a new column with the IDENTITY property:

    ALTER TABLE MyTable ADD NewID int IDENTITY(1,1) not null
    

    Unfortunately, you're not then able to assign the old ID values to this new column. If you want to assign the ID values, and then let IDENTITY take over, you'd be better off creating a new table with the structure you want, then importing data from the old table (you can use IDENTITY_INSERT to assign values to the IDENTITY column).

    You would then drop the old table and rename the new table, if required.

    0 讨论(0)
提交回复
热议问题