Groups | Blog | Home
all groups > sql server (alternate) > january 2004 >

sql server (alternate) : Locking Users Out of Table


Kristofer Andersson
1/30/2004 2:46:34 PM
Start a transaction, do a select top 1 * from my_table with (tablockx).
Should keep out everyone except those that do "with (nolock)" dirty reads
until your transaction is committed or rolled back. A global var used in the
SP can be used to flag that it is already running.

[quoted text, click to view]

Tim Morrison
1/30/2004 4:32:27 PM
SQL Server 2000, MSDE 2000

I have a procedure in my application that I would like only one user at a
time to be able to run. Is there a TSQL command I can run that will
esentially lock a set of tables so others cannot access the table until the
user is done with the procedure or until the user disconnects from that
session (in case of a hung app, I would like to lock released)

TIA

--
Tim Morrison

----------------------------------------------------------------------------
----

Vehicle Web Studio - The easiest way to create and maintain your vehicle
related website.
http://www.vehiclewebstudio.com

Simon Hayes
1/30/2004 6:51:06 PM

[quoted text, click to view]

One possibility is to use an application lock - see sp_getapplock and
sp_releaseapplock in Books Online - which your procedure would attempt to
acquire before continuing. Alternatively, you can use a table column as a
flag to indicate whether or not the procedure is already running, but in
this case you have to handle the case of dropped connections yourself.

Simon

Erland Sommarskog
1/30/2004 11:50:49 PM
Tim Morrison (sales@kjmsoftware.com) writes:
[quoted text, click to view]

First you need to decide. Is it this particular procedure that you
want to serialize, or do you want to lock out any access to the tables?

Simon suggested application locks, and I think this is the best, as
this can be restricted to the procedure alone. The best is to have
a transaction enclosed, so that when you commit or rollback the lock
is released. But if don't want to have the entire procedure within
a transaction, or want to have several transactions, you can also take
out an application lock on session level.

For more details, look up sp_getapplock in Books Online.

--
Erland Sommarskog, SQL Server MVP, sommar@algonet.se

Books Online for SQL Server SP3 at
AddThis Social Bookmark Button