Adding an identity to an existing column

后端 未结 19 2053
温柔的废话
温柔的废话 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:59

    Simple explanation

    Rename the existing column using sp_RENAME

    EXEC sp_RENAME 'Table_Name.Existing_ColumnName' , 'New_ColumnName', 'COLUMN'

    Example for Rename :

    The existing column UserID is renamed as OldUserID

    EXEC sp_RENAME 'AdminUsers.UserID' , 'OldUserID', 'COLUMN'
    

    Then add a new column using alter query to set as primary key and identity value

    ALTER TABLE TableName ADD Old_ColumnName INT NOT NULL PRIMARY KEY IDENTITY(1,1)
    

    Example for Set Primary key

    The new created column name is UserID

    ALTER TABLE Users ADD UserID INT NOT NULL PRIMARY KEY IDENTITY(1,1)
    

    then Drop the Renamed Column

    ALTER TABLE Table_Name DROP COLUMN Renamed_ColumnName
    

    Example for Drop renamed column

    ALTER TABLE Users DROP COLUMN OldUserID
    

    Now we've adding a primarykey and identity to the existing column on the table.

提交回复
热议问题