Adding an identity to an existing column

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

    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

提交回复
热议问题