renumber primary key

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

    This may or not be MS SQL specific, but: TRUNCATE TABLE resets the identity counter, so one way to do this quick and dirty would be to 1) Do a Backup 2) Copy table contents to temp table: 3) Copy temp table contents back to table (which has the identity column):

    SELECT Field1, Field2 INTO #MyTable FROM MyTable
    
    TRUNCATE TABLE MyTable
    
    INSERT INTO MyTable
    (Field1, Field2)
    SELECT Field1, Field2 FROM #MyTable
    
    SELECT * FROM MyTable
    -----------------------------------
    ID    Field1    Field2
    1     Value1    Value2
    

提交回复
热议问题