How do I get first unused ID in the table?

后端 未结 6 1930
温柔的废话
温柔的废话 2021-01-12 23:58

I have to write a query wherein i need to allocate a ID (unique key) for a particular record which is not being used / is not being generated / does not exist i

6条回答
  •  自闭症患者
    2021-01-13 00:33

    Depends on what you mean by "next id" and how it's generated.

    If you're using a sequence or identity in the database to generate the id, it's possible that the "next id" is not 3 or 4 but 6 in the case you've presented. You have no way of knowing whether or not there were values with id of 3 or 4 that were subsequently deleted. Sequences and identities don't necessarily try to reclaim gaps; once they're gone you don't reuse them.

    So the right thing to do is to create a sequence or identity column in your database that's automatically incremented when you do an INSERT, then SELECT the generated value.

提交回复
热议问题