LockTable/ReadIsolation(UpdLock) should be placed before a read operation, if a write operation is performed later #737
christophstuber
started this conversation in
New Rule
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Recently stumbled over a piece of code like this:
With native DB this was the way to go.
LockTable
was it's own operation and more importantly, it locked the entire table, which is where the (now misleading) name comes from and is why it should always be used as late as possible.But with SQL DB things work differently.
LockTable
itself doesn't call a DB operation, but instead addsWITH(UPDLOCK)
to the next read operation on that record. Therefore it must be placed before the first read.Maybe this can be used as a starting point for a more general rule. Lock before you write
Typical code you find is like this:
Because the record is read with
READUNCOMMITED
, SQL Server cannot guarantee at the time ofModify()
, thatThis leads to an additional implicit read right before the modify, this time with
UPDLOCK
set. This is also where the Another user has modified the record comes from. Depending on how much is done between the read and the write a rather large rollback will be done.The following rules should apply:
Modifiy
,Delete
orRename
, the record should be read withLockTable
or betterReadIsolation(IsolationLevel::UpdLock)
. ForFindSet
, theForUpdate
parameter can also be used.Insert
is context dependent. With ledger tables it's required to guarantee no gaps in Entry Nos., in all other cases it can even be bad for performance and concurrency.Beta Was this translation helpful? Give feedback.
All reactions