sqlsql-servert-sqlsql-server-2008

How to update Identity Column in SQL Server?


I have SQL Server database and I want to change the identity column because it started with a big number 10010 and it's related with another table, now I have 200 records and I want to fix this issue before the records increases.

What's the best way to change or reset this column?


Solution

  • You can not update identity column.

    SQL Server does not allow to update the identity column unlike what you can do with other columns with an update statement.

    Although there are some alternatives to achieve a similar kind of requirement.

    • When Identity column value needs to be updated for new records

    Use DBCC CHECKIDENT which checks the current identity value for the table and if it's needed, changes the identity value.

    DBCC CHECKIDENT('tableName', RESEED, NEW_RESEED_VALUE)
    
    • When Identity column value needs to be updated for existing records

    Use IDENTITY_INSERT which allows explicit values to be inserted into the identity column of a table.

    SET IDENTITY_INSERT YourTable {ON|OFF}
    

    Example:

    -- Set Identity insert on so that value can be inserted into this column
    SET IDENTITY_INSERT YourTable ON
    GO
    -- Insert the record which you want to update with new value in the identity column
    INSERT INTO YourTable(IdentityCol, otherCol) VALUES(13,'myValue')
    GO
    -- Delete the old row of which you have inserted a copy (above) (make sure about FK's)
    DELETE FROM YourTable WHERE ID=3
    GO
    --Now set the idenetity_insert OFF to back to the previous track
    SET IDENTITY_INSERT YourTable OFF