Adding auto incrementing primary key to an existing table in SQL SERVER 2005

前端 未结 5 1482
逝去的感伤
逝去的感伤 2021-01-14 11:26

I have a table with 8,000 rows of data and will be adding more. but I forgot to put a primary key in the beginning. so that each row has a unique key. later i added a primar

5条回答
  •  旧时难觅i
    2021-01-14 12:13

    As per your requirement you just needed a sql query that will update the entire table with the new primary key values in an incremental fashion. Here is is :

    UPDATE myTable
    SET ID = ID + 1
    

    Where ID is the PK field name

    Once Updated do not forget to add identity column as shown below :

    ALTER TABLE table
    ADD ID INT IDENTITY
    
    ALTER TABLE table
    ADD CONSTRAINT PK_table
    PRIMARY KEY(ID)
    

提交回复
热议问题