Question

Simplest example: I've got the following table:

create table test
    ( ID int identity (1,1) not null primary key,
      text char(20) not null
    )

I have already created 3 values:

  • (1,a)
  • (2,b)
  • (3,c)

Now I delete (2,b), and my rows are (1,a) and (3,c).

  • Is it possible to make it automatically (1,a) and (2,c)?
  • Or do I have to create a procedure?
Était-ce utile?

La solution

No, and you shouldn't. There are too many ways that this can go bad - suppose you had related records in another table with 2 as a foreign key - instead of being orphaned (and easily identified as such) they would instead be related to a different (incorrect) record.

In addition, IDENTITY values are usually used as the clustered index (meaning they determine the physical storage location of the record). If you change the value, the data will have to be physically relocated -which wont hurt anything but will cause unnecessary I/O.

IDENTITY values are not guaranteed to be consecutive, they're guaranteed to be unique. If you need consecutive numbers, the best way is to derive that in your output by adding a ROW_NUMBER column:

SELECT 
    ROW_NUMBER() OVER (ORDER BY ID) RowNum,
    ID,
    text
FROM test

However note that RowNum will be DIFFERENT if records in the middle are deleted (as you could guess). So you can't build any relationships off of that value - you can just use it to show consecutive ordering.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top