renumber primary key

前端 未结 6 1005
天命终不由人
天命终不由人 2021-01-12 03:31

How would I reset the primary key counter on a sql table and update each row with a new primary key?

6条回答
  •  走了就别回头了
    2021-01-12 04:32

    you could do it in the following steps:

    • create copy of yourTable with extra column new_key
    • populate copyOfYourTable with the affected rows from yourTable along with desired values of new_key
    • temporarily disable constraints
    • update all related tables to point to the value of new_key instead of the old_key
    • delete affected rows from yourTable
    • SET IDENTITY_INSERT [yourTable] ON
    • insert affected rows again with the new proper value of the key (from copy table)
    • SET IDENTITY_INSERT [yourTable] OFF
    • reseed identity
    • re-enable constraints
    • delete the copyOfYourtable

    But as others said all that work is not needed. I tend to look at the identity type primary keys as if they were equivalent of pointers in C, I use them to reference other objects but never modify of access them explicitly

提交回复
热议问题