How do I add auto_increment to a column in SQL Server 2008

前端 未结 5 799
走了就别回头了
走了就别回头了 2021-01-12 21:10

I am using SQL Server 2008 and a primary key of a database table I am using is not an IDENTITY column (not sure why). I need to change that.

I am in SQ

5条回答
  •  无人及你
    2021-01-12 21:52

    You can't use ALTER TABLE ... ALTER COLUMN to modify a column to have an identity property. You'll need to

    • drop the primary key constraint and any foreign key constraints referencing the column in question in your table.
    • add a new column with the identity property. It should have the same type (int, I presume) as the existing column.
    • update the table to seed the new column with the values of the existing column.
    • alter the new column to make it non-nullable.
    • drop the old/existing column.
    • rename the new column so that its name is the same as that of the old column.
    • Recreate the primary key and foreign key references you dropped in the 1st step.

    Simple! Or something.

提交回复
热议问题