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
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)
Now remove column 'EmployeeId' from 'Employee' table
ALTER TABLE Employee DROP COLUMN EmployeeId
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].'###
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]
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
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'
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