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 per my current condition, I follow this approach. I want to give identity to a primary table after data inserted via script.
As I want to append identity, so it always start from 1 to End of record count that I want.
--first drop column and add with identity
ALTER TABLE dbo.tblProductPriceList drop column ID
ALTER TABLE dbo.tblProductPriceList add ID INT IDENTITY(1,1)
--then add primary key to that column (exist option you can ignore)
IF NOT EXISTS (SELECT * FROM sys.key_constraints WHERE object_id = OBJECT_ID(N'[dbo].[PK_tblProductPriceList]') AND parent_object_id = OBJECT_ID(N'[dbo].[tblProductPriceList]'))
ALTER TABLE [tblProductPriceList] ADD PRIMARY KEY (id)
GO
This will create the same primary key column with identity
I used this links : https://blog.sqlauthority.com/2014/10/11/sql-server-add-auto-incremental-identity-column-to-table-after-creating-table/
Add primary key to existing table