renumber primary key

前端 未结 6 1006
天命终不由人
天命终不由人 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:36

    If this is Microsoft's SQL Server, one thing you could do is use the [dbcc checkident](http://msdn.microsoft.com/en-us/library/ms176057(SQL.90).aspx)

    Assume you have a single table that you want to move around data within along with renumbering the primary keys. For the example, the name of the table is ErrorCode. It has two fields, ErrorCodeID (which is the primary key) and a Description.

    Example Code Using dbcc checkident

    -- Reset the primary key counter
    dbcc checkident(ErrorCode, reseed, 7000)
    
    -- Move all rows greater than 8000 to the 7000 range
    insert into ErrorCode
    select Description from ErrorCode where ErrorCodeID >= 8000
    
    -- Delete the old rows
    delete ErrorCode where ErrorCodeID >= 8000
    
    -- Reset the primary key counter
    dbcc checkident(ErrorCode, reseed, 8000)
    

    With this example, you'll effectively be moving all rows to a different primary key and then resetting so the next insert takes on an 8000 ID.

    Hope this helps a bit!

提交回复
热议问题