Quantcast
Channel: SQL Server Database Engine forum
Viewing all articles
Browse latest Browse all 12963

Lock granularity

$
0
0

Hi,

I have a situation where I don't understand why one stored procedure is blocking another. The procedure issues an UPDATE according to this pattern:

UPDATE [T] SET Col1 = Col1 + 1 WHERE Col2_FK = @id

Col1 here is a regular attribute and Col2_FK is a foreign key. Thanks to a mismatch between data model and application model this update will always affect exactly one row. (Col2_FK has a constraint and is NOT NULL and I've furthermore done a count(*) grouped by Col2_FK having count(*) > 1 to verify there are no two rows in T with the same value in Col2_FK.)

If I open up two tabs in management studio, start a transaction in each, and then run the procedure first in tab #1 and then #2 withdifferent @id, the second session is always blocked by the first (until I commit or rollback).

I would expect an X lock at row level only, with IX on the page and table. But then the two transactions would run concurrently, since they do not in fact share any data. In other words, I would expect #1 to block #2 only when the value of @id is the same in both transactions.

Table T has a clustered index (of type int identity(1,1)), and so does the table referenced by the FK. There's no index for the FK itself.

I have tried to use SQL Profiler to understand what's going on, but the trace contains only mysterious IDs (that look suspiciously like addresses - it seems to always be valid hex values) and I don't understand if the locks are row locks or page locks.

If the update is done based on PK instead of FK, it appears only row locks are held and both transactions can run concurrently. 

There's so little data in the table it's probably all on the same page (data space used, as viewed in object explorer details in management studio, is 8KB = 1 page). I therefore suspect an X lock exists at the page level, but I don't understand WHY the database engine would go ahead and lock in practice the entire table just because I update a single row in it (out of ~100 small rows).



Viewing all articles
Browse latest Browse all 12963

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>