Does SQL Server guarantee sequential inserting of an identity column?

后端 未结 5 1234
情话喂你
情话喂你 2021-02-13 15:12

In other words, is the following \"cursoring\" approach guaranteed to work:

  1. retrieve rows from DB
  2. save the largest ID from the returned records for later,
5条回答
  •  猫巷女王i
    2021-02-13 15:57

    I think this can go wrong depending on the duration of transactions Consider the following sequence of events:

    1. Transaction A starts
    2. Transaction A performs insert - This creates a new entry in the identity column
    3. Transaction B starts
    4. Transaction B performs insert - This creates a new entry in the identity column
    5. Transaction B commits
    6. Your code performs its select and sees the identity value from the 2nd transaction
    7. Transaction A commits -

    The row inserted by Transaction A will never be found by your code. It was not already committed when step 6 was performed. And when the next query is performed it will not be found, because it has a lower value in the identity column than the query is looking for.

    It could work if you perform the query with a read-uncommitted isolation mode

提交回复
热议问题