首页 > 解决方案 > 如何用另一个存储过程执行一个存储过程?

问题描述

我有会话锁定程序,当一个程序在一个会话中运行时,如果同一个程序正在运行另一个会话,它将在第一个会话完成之前不会执行

EXEC dbo.[system-LockProcedure]'dbo.usp_Test1' 

它工作正常,我没有任何问题,但是当我想使用输入参数执行过程时,出现错误:

DECLARE @threadid INT = 0;

EXEC [util].[system-LockProcedure] N'[dbo].[usp_Test1] @threadid=@threadid', 
                       N'@threadid INT', 
                         @threadid=@threadid

错误:

[dbo].[usp_Test1] 需要参数 @threadid,但未提供该参数。

当我执行一个没有输入参数的过程时,它工作正常,当我想执行一个带有输入参数的过程时,它会抛出一个错误。

请建议如何解决这个问题。

系统锁定程序:

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

标签: sqlsql-servertsql

解决方案


尝试这个:

DECLARE @threadid INT = 0;

DECLARE @ExecuteString NVARCHAR(MAX) = N'[dbo].[usp_Test1] @threadid= ' + CAST(@threadid AS VARCHAR(4)) + ';'

EXEC [util].[system-LockProcedure] @ExecuteString;

推荐阅读