Does SQL Server guarantee sequential inserting of an identity column?

后端 未结 5 1220
情话喂你
情话喂你 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条回答
  •  再見小時候
    2021-02-13 15:58

    Guaranteed as in absolutely under no circumstances whatsoever could you possibly get a value that might be less than or equal to the current maximum value? No, there is no such guarantee. That said, the circumstances under which that scenario could happen are limited:

    1. Someone disables identity insert and inserts a value.
    2. Someone reseeds the identity column.
    3. Someone changes the sign of the increment value (i.e. instead of +1 it is changed to -1)

    Assuming none of these circumstances, you are safe from race conditions creating a situation where the next value is lower than an existing value. That said, there is no guarantee that the rows will be committed in the order that of their identity values. For example:

    1. Open a transaction, insert into your table with an identity column. Let's say it gets the value 42.
    2. Insert and commit into the same table another value. Let's say it gets value 43.

    Until the first transaction is committed, 43 exists but 42 does not. The identity column is simply reserving a value, it is not dictating the order of commits.

提交回复
热议问题