DBCC CHECKIDENT Sets Identity to 0

前端 未结 10 1307
长发绾君心
长发绾君心 2020-12-07 21:55

I\'m using this code to reset the identity on a table:

DBCC CHECKIDENT(\'TableName\', RESEED, 0)

This works fine most of the time, with the f

10条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-07 22:15

    You are right in what you write in the edit of your question.

    After running DBCC CHECKIDENT('TableName', RESEED, 0):
    - Newly created tables will start with identity 0
    - Existing tables will continue with identity 1

    The solution is in the script below, it's sort of a poor-mans-truncate :)

    -- Remove all records from the Table
    DELETE FROM TableName
    
    -- Use sys.identity_columns to see if there was a last known identity value
    -- for the Table. If there was one, the Table is not new and needs a reset
    IF EXISTS (SELECT * FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = 'TableName' AND last_value IS NOT NULL) 
        DBCC CHECKIDENT (TableName, RESEED, 0);
    

提交回复
热议问题