我一直在使用此sp_getapplock锁定资源的会话。 以下是过程:
CREATE Procedure [dbo].[system-LockProcedure] @procname varchar(200)
AS
--BEGIN TRAN
BEGIN
DECLARE @lockreturn int,
@lockresource varchar(200) --sysname
SELECT @lockresource = @procname
-- The below line will try to acquire an exclusive lock on the PROC for the session, If the Proc is already in execution the @lockreturn value will be > 0
EXEC @lockreturn = sp_getapplock @lockresource, @LockMode = 'Exclusive', @LockOwner = 'Session' , @LockTimeout = 100
Print @lockreturn
IF @lockreturn <> 0
BEGIN
RAISERROR ('Another instance of the procedure is already running', 16, 1)
RETURN
END
-- The Code to be executed goes here. All the core logic of the proc goes here..
Print 'Procedure Execution Started for user: ' + cast (CURRENT_USER as nvarchar(20))+ ' for session: ' + cast (@@SPID as nvarchar(10))
-- This is just to make the system wait for 30 seconds and make sure if there is any concurrent execution triggered will fail
exec @lockresource
Print 'Procedure Execution Ended for user: ' + cast (CURRENT_USER as nvarchar(20))+ ' for session: ' + cast (@@SPID as nvarchar(10))
Print @lockreturn
-- This is to release the lock once the SP code is ran completely
EXEC sp_releaseapplock @lockresource , 'Session'
-- END TRY
END
我们也可以在您本地执行此过程以进行测试。
当我在一个会话中执行该过程时,如果有人想要执行此存储过程,则它将显示一条消息,表明它已在其他会话中打开。 使用资源名称(也是对象
)执行此过程时EXEC dbo.[system-LockProcedure]'dbo.usp_Test1'
一切正常
EXEC dbo.[system-LockProcedure]'dbo.usp_Test2'
具有输入参数,并要求输入参数
Error :
Msg 201, Level 16, State 4, Procedure USP_Test2, Line 23
Procedure or function 'USP_Test2' expects parameter '@ThreadID', which was not supplied.