snippetsqlMinor
How to lock a Row while I'm using it
Viewed 0 times
whileusinghowrowlock
Problem
I want to be able to Lock a row, select it, increment its value, and then release the lock. (without lockin the other rows, so that other connections can work with the rest of the table)
I've found this
My problem is I cant do
until I commit my previous transaction, why is rowlock locking the whole table?
edit:
Does this code guarantees that the data of the selected row is not update during this update command?
I've found this
BEGIN TRAN SELECT * FROM tablename WITH (HOLDLOCK, ROWLOCK)
WHERE ID = 1My problem is I cant do
UPDATE tablename
SET columnName = -1
WHERE ID = 2until I commit my previous transaction, why is rowlock locking the whole table?
edit:
Does this code guarantees that the data of the selected row is not update during this update command?
UPDATE [tablename] WITH (ROWLOCK)
SET columnName = columnName + 5
WHERE ID = 1Solution
Based on your edit, all writes lock exclusively.
No other process can read the row(s) being written unless
There is usually no need to add lock hints in day to day code.
As to why you (apparently) have a table lock, this can be caused by no index on ID. The table is being locked because all rows have to be looked at.
No other process can read the row(s) being written unless
- you've been silly and are using NOLOCK
- you have snapshot isolation where the last committed row is read
There is usually no need to add lock hints in day to day code.
As to why you (apparently) have a table lock, this can be caused by no index on ID. The table is being locked because all rows have to be looked at.
Context
StackExchange Database Administrators Q#14263, answer score: 6
Revisions (0)
No revisions yet.