views:

374

answers:

4

I have a stored procedure for SQL Server 2000 that can only have a single instance being executed at any given moment. Is there any way to check and ensure that the procedure is not currently in execution?

Ideally, I'd like the code to be self contained and efficient (fast). I also don't want to do something like creating a global temp table checking for it's existence because if the procedure fails for some reason, it will always be considered as running...

I've searched, I don't think this has been asked yet. If it has been, sorry.

+1  A: 

how about locking a dummy table? That wouldn't cause deadlocks in case of failures.

palindrom
i can't see how this would help in any way. can you elaborate more?
Mladen Prajdic
A: 

At the start of the procedure check if piece of data is 'locked' if not lock it

At end of procedure unlock the piece of data.

ie

SELECT @IsLocked=IsLocked FROM CheckLockedTable Where spName = 'this_storedProcedure'

IF @IsLocked = 1
    RETURN
ELSE
    UPDATE CheckLockedTable SET IsLocked = 1 Where spName = 'this_storedProcedure'

.
.
.

-- At end of Stored Procedure
    UPDATE CheckLockedTable SET IsLocked = 0 Where spName = 'this_storedProcedure'
Paul Rowland
How would I accomplish this?
Frank V
Good solution but it is not self contained...
Frank V
+6  A: 

yes there is a way. use what is known as SQL Server Application locks.

EDIT: yes this also works in SQL Server 2000.

Mladen Prajdic
@LFSR Consulting: you are wrong about that.
Mladen Prajdic
@Mladen, sorry you're right, my bad
Gavin Miller
I've not tried it yet but this looks like the answer I need. Thanks!
Frank V
+2  A: 

You can use sp_getapplock sp_releaseapplock as in the example found at Lock a Stored Procedure for Single Use Only.

But, is that what you are really trying to do? Are you trying to get a transaction with a high isolation level? You would also likely be much better off handling that type of concurrency at the application level as in general higher level languages have much better primitives for that sort of thing.

JP Alioto