Adding an identity to an existing column

后端 未结 19 2092
温柔的废话
温柔的废话 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 14:07

    As I understood in normal cases we are creating a table with Primary key which is having Identity property
    So Rename or Delete a column which is associated with Primary Key constraint will not be possible because constraint Rules are validating column structure.
    Tto achieve this we have to process some steps in the following way:
    Let us assume TableName = 'Employee' and ColumnName = 'EmployeeId'

    1. Add new column 'EmployeeId_new' in the 'Employee' table
    ALTER TABLE Employee ADD EmployeeId_new INT IDENTITY(1,1)

    1. Now remove column 'EmployeeId' from 'Employee' table
      ALTER TABLE Employee DROP COLUMN EmployeeId

    2. This will throw error because of Primary Key Constraint rules are applicable and validating column structure.
      *### 'Msg 5074, Level 16, State 1, Line 1 The object [PK_dbo.Employee] is dependent on colmn [EmployeeId].'###

    3. So we have to remove the Primary Key constraint first from the table 'Employee' then we can remove the column
      ALTER TABLE Employee DROP constraint [PK_dbo.Employee]

    4. Now we can remove the column 'EmployeeId' from 'Employee' table as did in the previous step where we got error
      ALTER TABLE Employee DROP COLUMN EmployeeId

    5. Now Column 'EmployeeId' removed from table So we will Rename the newly added new column 'EmployeeId_new' with 'EmployeeId'
      sp_rename 'Employee.EmployeeId', 'EmployeeId_new', 'COLUMN'

    6. To rearrange the table in the same form as It was, we have to add Primary Key Constraint for the column 'EmployeeId'
      ALTER TABLE Employee add constraint [PK_dbo.Employee] primary key (EmployeeId)

    8. Now the table 'Employee' with 'EmployeeId' is modified for Identity rules along with existing primary key constraint

提交回复
热议问题