Does SQL Server guarantee sequential inserting of an identity column?

后端 未结 5 1226
情话喂你
情话喂你 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:40

    The only thing that SQL Server guarantees is that your IDENTITY column will always be incremented.

    Things to consider though:

    1. If a fail INSERT occurs, the IDENTITY column will get incremented anyhow;
    2. If a rollback occurs, the IDENTITY column will not return to its previous value;

    Which explains why SQL Server doesn't guarantee sequential INDENTITY.

    There is a way to reset an IDENTITY column like so using the DBCC command. But before doing so, please consider the following:

    1. Ensure your IDENTITY column is not referenced by any other table, as your foreign keys could be not updated with it, so big troubles ahead;
    2. You might use the SET IDENTITY_INSERT ON/OFF instruction so that you may manually specify the IDENTITY while INSERTing a row (never forget to turn it on afterward).

    An IDENTITY column is one of the most important element never to be changed in DBRMs.

    Here is a link that should help you: Understanding IDENTITY columns

    EDIT: What you seem to do shall work as the IDENTITY column from LastMax will always increment for each INSERTed row. So:

    1. Selecting rows from data table;
    2. Saving LastMax state;
    3. Selecting rows where Id > LastMax.

    3) will only select rows where the IDENTITY column will be greater than LastMax, so inserted since LastMax has been saved.

提交回复
热议问题