开发者

SQL Server transactions / concurrency confusion - must you always use table hints?

开发者 https://www.devze.com 2023-01-21 13:09 出处:网络
When you create a SQL Server transaction, what gets locked if you do not specify a table hint? In order开发者_StackOverflow to lock something, must you always use a table hint? Can you lock rows/table

When you create a SQL Server transaction, what gets locked if you do not specify a table hint? In order开发者_StackOverflow to lock something, must you always use a table hint? Can you lock rows/tables outside of transactions (i.e. in ordinary queries)? I understand the concept of locking and why you'd want to use it, I'm just not sure about how to implement it in SQL Server, any advice appreciated.


You should use query hints only as a last resort, and even then only after expert analysis. In some cases, they will cause a query to perform badly. So, unless you really know what you are doing, avoid using query hints.

Locking (of various types) happens automatically everytime you perform a query (unless NOLOCK is specified). The default Transaction Isolation level is READ COMMITTED

What are you actually trying to do?

Understanding Locking in SQL Server


"Can you lock rows/tables outside of transactions (i.e. in ordinary queries)?"

You'd better understand that there are no ordinary queries or actions in SQL Server, they are ALL, without any exceptions, transactional. This is how ACID-ness is achieved, see, for ex., [1]. If client tools or developer interactively do not specify transaction explicitly with BEGIN TRANSACTION and COMMIT/ROLLBACK, then implicit transactions are used.

Also, transaction is not synonym of locking/locks engagement. There is a plethora of mechanisms to control concurrency without locking (for example, versioning. etc.) as well as READ UNCOMMITTED transaction "isolation" (in this case, absence of any isolation) level does not control it at all.

Update2:

In order to lock something, must you always use a table hint?

As far as, transaction isolation level is not READ UNCOMMITTED or one of row-versioning (snapshot) isolation levels, for ex., default READ COMMITTED or set by, for ex.,

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE  

the locks are issued (I do not know where to start and how to end this topic[2]). Table hints, which can be used in statements, override these settings.

[1]
Paul S. Randal. Understanding Logging and Recovery in SQL Server
What is Logging?
http://technet.microsoft.com/en-us/magazine/2009.02.logging.aspx#id0060003
[2]
Insert trailing ) upon clicking this link
http://en.wikipedia.org/wiki/Isolation_(database_systems)

Update:
5 min ago I had reputation 784 (the same as 24h ago) and, now, without any visible downvotes, it dropped to 779.
Where can I ask this question if I am banned from meta.stackoverflow.com?

0

精彩评论

暂无评论...
验证码 换一张
取 消