Filling the gaps in values of IDENTITY column

后端 未结 4 1631
南旧
南旧 2020-12-19 20:15

I have a table with an IDENTITY column

[Id] int IDENTITY(1, 1) NOT NULL

After some rows beeing added/removed I end with gaps in Id values:<

相关标签:
4条回答
  • 2020-12-19 20:46

    I would strongly recommend that you leave the identity values as they are.

    if this ID column is used as a foreign key on another table, changing them will get complicated very quickly.

    if there is some business logic where they must be sequential then add a new column ID_Display where you can update them using ROW_NUMBER() and keep them pretty for the end user. I never let end users see and/or dictate how I create/populate/store the data, and if they are bothering you about the IDs then show them some other data that looks like an ID but is not a FK or PK.

    0 讨论(0)
  • 2020-12-19 20:46

    Well as far as I know the only way you can is manually update the values by turning Identity insert on..but you should really avoid doning such a thing in first place..also if you truncate the table it will not have those gaps.

    0 讨论(0)
  • 2020-12-19 20:47

    I think it's pretty easy to create a 2nd table with the same schema, import all the data (except for the identity column of course; let the 2nd table start renumbering) from the first table, drop the first table and rename the 2nd to the original name.

    Easiness may be in question if you'd have a ton of FK relationships to rebuild with other tables etc.

    0 讨论(0)
  • 2020-12-19 20:51

    I cannot control the part which requires ID columns to be in sequence.

    This sounds like there is program logic which assumes there are no gaps--correct?

    I need this to keep two different databases in sync.

    It's still not clear what you mean. If the actual values in the IDENTITY column are not meaningful (not used as foreign keys by other tables), you can just do this:

    DELETE FROM db1.table
    SELECT col1, col2, col3 /* leave out the IDENTITY column */ 
    INTO db1.table FROM db2.table
    
    0 讨论(0)
提交回复
热议问题