Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

sql server - I need row-level locking

This is an extension to Is it possible to force row level locking in SQL Server?. Here is the use case

I have accounts table having account numbers, balances, etc. This table is being used by many applications. It is quite possible that while I am modifying an account, someone else is modifying another account. So the expected behavior is that I would lock my account(ROW) and the other use will lock his(another ROW).

But SQL Server 2008 R2 escalates this locking to page/table and the second user gets timeout exception. I have tried all the solutions mentioned in the referenced question but nothing is working.

How can I force SQL Server to lock a row-level lock only OR how can I modify this model in a way that it will work with page/table locking?

EDIT The update is targeting a single record via its PK and it is indexed so only ONE ROW is being updated/locked and the process takes not more than a minute

Edit Now it looks something weird is happening. I am using an ORM library for DAL which is opening more than one connections and i have raised the question to their support. But, for testing purpose, i opened two sessions on query tool and did following

Session # 1
begin tran
UPDATE myTable SET COL_1 = COL_1 WHERE COL_1 = 101;

Session # 2
SELECT COL_1 FROM myTable WHERE COL_1 = 101;

The query in Session # 2 times out !!! Queries for other values of COL_1 are working fine. Now it looks SELECT is blocked for a session if the same record is in edit mode in another session.

Though Oracle does support selection of a row (with default params/no keywords) while it is being modified by other session, SQL Server does not (with default params/no keywords), so it seems the problem is with the library.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

SQL Server always uses row-level locking by default .... so what exactly is it that you need??

If you lock more than a certain amount of rows (roughly 5000), then SQL Server will do lock escalation (lock the table instead of more than 5000 rows individually) to optimize performance and optimize on resource usage - but that's a good thing! :-)

There are ways to turn this off entirely - but those are NOT recommended! since you're messing with a very fundamental mechanism inside SQL Server's storage engine.

See:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...