MarcoP wrote:
Otis wrote:
Lock a table, or lock a few rows? Locking a table is pretty severe (as in: it will block other apps)
I would say just lock the rows I am currently working with.
I have the following table:
Amount Maximum Used
25 10 0
100 8 2
Basically, we are distributing out awards and we only have a given amount to distribute and we have to stay within the max range.
I only select a subset of the records and I need to lock those records so I can read them and then update the used column.
Short answer: RepeatableRead is the level you need to use - it basically locks all the rows you select during the transaction so they cannot be updated during the transaction.
Correct answer: this is potentially a larger subject than can be dealt with in the average forum reply so reading up on isolation levels and locking with particular reference to the db you are using is advised.
Helpful answer (?): As pointed out, depending on database vendor, version and the isolation level of other connections, other transactions attempting to access these rows (and possibly others) may block/timeout while you have the locks so keep the transaction short. I.e. database locks are only really useful for transactions that do not wait on user interaction.
Another simple technique that may be helpful (depending on the nature of the problem) is to set a check contraint to prevent the Used column from exceeding the Maximum or Amount column. I.e. any update that would violate the contraint will fail - you would need to handle the failure appropriately.
HTH