Is this a continuation of When do I update / insert one row if it locks the entire table?
Here is my problem.
I have a table in which locks are stored, so that other records in the system do not need to do locks on shared resources, but they can still queue tasks so that they are performed one at a time.
When I access an entry in this lock table, I want to be able to lock it and update it (only one entry), without any other process that can do the same. I can do this with a lock hint like updlock .
What happens is that although Im uses a lock to lock records, it blocks the request to another process in order to change an absolutely unrelated row in the same table, which would also indicate updlock tell me with rowlock .
You can recreate this by creating a table
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO SET ANSI_PADDING ON GO CREATE TABLE [dbo].[Locks]( [ID] [int] IDENTITY(1,1) NOT NULL, [LockName] [varchar](50) NOT NULL, [Locked] [bit] NOT NULL, CONSTRAINT [PK_Locks] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 100) ON [PRIMARY] ) ON [PRIMARY] GO SET ANSI_PADDING OFF GO ALTER TABLE [dbo].[Locks] ADD CONSTRAINT [DF_Locks_LockName] DEFAULT ('') FOR [LockName] GO ALTER TABLE [dbo].[Locks] ADD CONSTRAINT [DF_Locks_Locked] DEFAULT ((0)) FOR [Locked] GO
Add two lines to lock with LockName = 'A and one for LockName =' B
Then create two queries to run in the transaction at the same time:
Request 1:
Commit Begin transaction select * From Locks with (updlock rowlock) where LockName='A'
Request 2:
select * From Locks with (updlock rowlock) where LockName='B'
Please note that I leave the transaction open so that you can see this problem, since it will not be visible without this open transaction.
When Query 1 starts, locks are problems for the row, and any subsequent requests for LockName = A will have to wait. This is the correct behavior.
If this is a little disappointing when you start Query 2 , you are locked until Query 1 ends, even think that these are unrelated entries. If you run Query 1 again, as soon as I can, it will transfer the previous transaction, Query 2 will start, and then Query 1 will block the record again.
Please offer some tips on how I can correctly pin ONLY one line, and also not prevent other elements from being updated.
PS. Holdlock also does not create the correct behavior after updating one of the rows.