How to re-seed a table identity in SQL Server 2008 and undo it all safely?

后端 未结 2 1170
遥遥无期
遥遥无期 2020-12-23 13:17

I need to do this for testing only, but then undo it when the test is done.

I have seen some tutorials online on how to re-seed a table, but not so much on how to un

相关标签:
2条回答
  • 2020-12-23 13:45

    The command to reset the identity property is

    DBCC CHECKIDENT (tablename, RESEED, new_reseed_value)
    

    When you want to set the column identity to 12345 you run this

    DBCC CHECKIDENT (beer, RESEED, 12345)
    

    When you want to delete test rows and restore the value to the previous value, you do the following.

    DELETE
    FROM beer
    WHERE beer_id >= 12345 ;
    
    DECLARE @NewSeed NUMERIC(10)
    SELECT @NewSeed = MAX(beer_id)
    FROM beer ;
    
    DBCC CHECKIDENT (beer, RESEED, @NewSeed)
    

    Here is a demonstration for your scenario. Note that the beer_id column is created with the IDENTITY (1, 1) property, which seeds the identity to 1 with an increment of 1.

    CREATE TABLE beer
        (        
        beer_id NUMERIC(10) IDENTITY (1,1) NOT NULL,
        mnemonic NVARCHAR(8)
        );
    
    GO
    
    INSERT INTO beer(mnemonic) VALUES ('Beer 1')
    INSERT INTO beer(mnemonic) VALUES ('Beer 2')
    
    SELECT *
    FROM beer ;
    
    DBCC CHECKIDENT (beer, RESEED, 12345)
    GO
    
    INSERT INTO beer(mnemonic) VALUES ('Beer 3')
    INSERT INTO beer(mnemonic) VALUES ('Beer 4')
    
    SELECT *
    FROM beer ;
    
    DELETE
    FROM beer
    WHERE beer_id >= 12345 ;
    
    DECLARE @NewSeed NUMERIC(10)
    SELECT @NewSeed = MAX(beer_id)
    FROM beer ;
    
    DBCC CHECKIDENT (beer, RESEED, @NewSeed)
    GO
    
    INSERT INTO beer(mnemonic) VALUES ('Beer 5')
    INSERT INTO beer(mnemonic) VALUES ('Beer 6')
    
    SELECT *
    FROM beer ;
    
    0 讨论(0)
  • 2020-12-23 13:52

    Sometimes we have Schema restriction from some users and thus causes error (Cannot find a table or object with the name "TableName". Check the system catalog), hence the best thing is to follow the below code.

    Schema.TableName should be enclosed in apostrophe

    DECLARE @SeedValue INT
    SET @SeedValue = (SELECT MAX(ColumnName) FROM Schema.TableName)
    DBCC CHECKIDENT ('Schema.TableName',RESEED,@SeedValue)
    
    0 讨论(0)
提交回复
热议问题