Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent a Stored Procedure from being executed twice at the same time

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.

like image 703
Frank V Avatar asked Jul 29 '09 21:07

Frank V


2 Answers

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

EDIT: yes this also works in SQL Server 2000.

like image 150
Mladen Prajdic Avatar answered Nov 07 '22 16:11

Mladen Prajdic


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.

like image 38
JP Alioto Avatar answered Nov 07 '22 18:11

JP Alioto