如何与另一个存储过程一起执行存储过程?

时间:2019-06-07 04:15:24

标签: sql sql-server tsql

我有会话锁定过程,该过程执行以下操作:如果一个过程在一个会话中运行,而同一过程在另一个会话中运行,则它将在第一个会话完成之前执行

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

2 个答案:

答案 0 :(得分:2)

尝试一下:

DECLARE @threadid INT = 0;

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

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

答案 1 :(得分:0)

在存储过程结束之前,使用要执行的过程名称及其相应的参数,例如:

Alter procedure Procedure1
As
begin
  select * from TableName
  Exec Procedure2 
end