HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Begin transaction doesn't lock table

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
doesntransactionbegintablelock

Problem

I have a table with this structure:

CREATE TABLE [dbo].[a](
    [id] [INT] IDENTITY(1,1) NOT NULL,
    [aa] [INT] NULL,
 CONSTRAINT [PK_a] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]


Then create new transaction and then update all records, but don't commit it.
So I have somethings like this:

BEGIN TRANSACTION

UPDATE dbo.a
SET aa=4


In new session I execute select and get result! and see old value before the update.

SELECT * FROM a


When I want to execute update, it waits for another transaction commit.

My question is:

When we update a table in a transaction we create a lock on it until commit transaction and no one can select from it, but why can I?

I have 57 records and when I check lock state on sql with this:

SELECT resource_type, request_mode, resource_description
FROM sys.dm_tran_locks
WHERE resource_type <> 'DATABASE'


I get result like this:

```
resource_type request_mode resource_description
------------------- ------------------- -------------------
OBJECT IX
OBJECT IX
OBJECT IX
KEY X (d8295d9f49e9)
PAGE X 4:17377
PAGE X 4:17376
PAGE X 4:17379
PAGE X 4:17378
PAGE X 4:17381
PAGE X 4:17380
PAGE X 4:17383
PAGE X 4:17382
EXTENT

Solution

If you can run a SELECT query against a table that another session has X locks on in Read Committed isolation, you must be in a database with READ_COMMITTED_SNAPSHOT set.

With READ_COMMITTED_SNAPSHOT Read Committed queries don't use Shared (S) locks. Instead if the query encounters a row that is locked or has been modified since the query started, it will read the "last known good" version of the row from the Version Store.

That's why you see the "old value before the update." If you need the other session's SELECT query to block until the transaction is complete, you can use a lock hint like UPDLOCK or READCOMMITTEDLOCK.

Context

StackExchange Database Administrators Q#214199, answer score: 5

Revisions (0)

No revisions yet.