Adding an identity to an existing column

后端 未结 19 2056
温柔的废话
温柔的废话 2020-11-21 13:16

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

19条回答
  •  你的背包
    2020-11-21 13:45

    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'
    

    Marc

提交回复
热议问题