In other words, is the following "cursoring" approach guaranteed to work:
LastMax
"SELECT * FROM MyTable WHERE Id > {0}", LastMax
In order for that to work, I have to be sure that every row I didn't get in step 1 has an Id greater than LastMax
. Is this guaranteed, or can I run into weird race conditions?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With