DBCC CHECKIDENT Sets Identity to 0

前端 未结 10 1312
长发绾君心
长发绾君心 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:24

    It seems ridiculous that you can't set/reset an identity column with a single command to cover both cases of whether or not the table has had records inserted. I couldn't understand the behavior I was experiencing until I stumbled across this question on SO!

    My solution (ugly but works) is to explicitly check the sys.identity_columns.last_value table (which tells you whether or not the table has had records inserted) and call the appropriate DBCC CHECKIDENT command in each case. It is as follows:

    DECLARE @last_value INT = CONVERT(INT, (SELECT last_value FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = 'MyTable'));
    IF @last_value IS NULL
        BEGIN
            -- Table newly created and no rows inserted yet; start the IDs off from 1
            DBCC CHECKIDENT ('MyTable', RESEED, 1);
        END
    ELSE
        BEGIN
            -- Table has rows; ensure the IDs continue from the last ID used
            DECLARE @lastValUsed INT = (SELECT ISNULL(MAX(ID),0) FROM MyTable);
            DBCC CHECKIDENT ('MyTable', RESEED, @lastValUsed);
        END
    

提交回复
热议问题