tags:

views:

110

answers:

2

Ex)

When should I use this statement:

DELETE TOP (@count) FROM ProductInfo WITH (ROWLOCK) WHERE ProductId = @productId_for_del;

And when should be just doing:

DELETE TOP (@count) FROM ProductInfo WHERE ProductId = @productId_for_del;

A: 

Rowlock is a query hint that should be used with caution (as is all query hints).

Omitting it will likely still result in the exact same behaviour and providing it will not guarantee that it will only use a rowlock, it is only a hint afterall. If you do not have a very in depth knowledge of lock contention chances are that the optimizer will pick the best possible locking strategy, and these things are usually best left to the database engine to decide.

ROWLOCK means that SQL will lock only the affected row, and not the entire table or the page in the table where the data is stored when performing the delete. This will only affect other people reading from the table at the same time as your delete is running.

If a table lock is used it will cause all queries to the table to wait until your delete has completed, with a row lock only selects reading the specific rows will be made to wait.

Deleting top N where in is a number of rows will most likely lock the table in any case.

Cobusve
+1  A: 

The with (rowlock) is a hint that instructs the database that it should keep locks on a row scope. That means that the database will avoid escalating locks to block or table scope.

You use the hint when only a single or only a few rows will be affected by the query, to keep the lock from locking rows that will not be deleted by the query. That will let another query read unrelated rows at the same time instead of having to wait for the delete to complete.

If you use it on a query that will delete a lot of rows, it may degrade the performance as the database will try to avoid escalating the locks to a larger scope, even if it would have been more efficient.

Guffa
Would you suggest to use it on a delete statement that deletes 2000 rows at a time in a loop?
RPS
@RPS: Generally, no. The database is normally smart enough to handle the locks on it's own. It might be useful if you are try to solve a specific problem, like deadlocks. I would suggest that you try to tweak the number of items you delete at a time before trying rowlock.
Guffa