In other words, is the following \"cursoring\" approach guaranteed to work:
The only thing that SQL Server guarantees is that your IDENTITY column will always be incremented.
Things to consider though:
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:
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:
- Selecting rows from data table;
- Saving LastMax state;
- 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.
Identities will will always follow the increment that defines the identity:
IDENTITY [(seed ,increment)] http://msdn.microsoft.com/en-us/library/aa933196(SQL.80).aspx
which can be positive or negative (you can have it increment forward or backwards). If you set your identity to increment forward, your identity values will always be larger than the previous, but you may miss some, if you rollback an INSERT.
Yes, if you set your identity increment to a positive value your loop logic will work.
The only time records might get inserted that you wouldn't get would be if someone turns the identity insert on and manually inserts a record to a skipped id (or in some cases to a negative number). This is a fairly rare occurance and generally would only be done by a system admin. Might be done to reinsert an accidentally deleted record for instance.
I think this can go wrong depending on the duration of transactions Consider the following sequence of events:
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
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:
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:
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.