views:

36

answers:

2

When you create a SQL Server transaction, what gets locked if you do not specify a table hint? In order 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.

+2  A: 

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

Mitch Wheat
*What are you actually trying to do?* - I have never really had to do much transactional or highly concurrent SQL work, but it looks like I may have to soon and I'm just trying to get to grips with the broad concepts I need to understand ..
flesh
+1  A: 

"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?

vgv8
why are you banned from meta? i guess it could be someone removing an upvote on one of your answers (wasnt me)
flesh