2017-08-17 137 views
1

我需要經常使用TRY..CATCH塊執行存儲過程。 因此,我寫一個存儲過程包括TRY..CATCH塊+一個輸入參數:SQL Server 2012 - 將存儲過程名稱傳遞給另一個存儲過程

CREATE PROCEDURE [dbo].[exec_sp_with_try_catch] 
    (@pnvcSPName NVARCHAR(100)) 
AS 
    DECLARE @ErrorMessage NVARCHAR(4000); 
    DECLARE @ErrorSeverity INT; 
    DECLARE @ErrorState INT; 
BEGIN 
    BEGIN TRY 
     exec @pnvcSPName; 
    END TRY 
    BEGIN CATCH 
     SELECT @ErrorMessage = ERROR_MESSAGE(), 
       @ErrorSeverity = ERROR_SEVERITY(), 
       @ErrorState = ERROR_STATE(); 

     RAISERROR(@ErrorMessage, -- Message text. 
       @ErrorSeverity, -- Severity. 
       @ErrorState -- State. 
     ); 

     IF XACT_STATE() <> 0 
      ROLLBACK TRANSACTION; 
    END CATCH 

END; 

然後,我可以直接使用上述的存儲過程,如果我想與try...catch塊以執行存儲過程:

exec [dbo].[exec_sp_with_try_catch] @pnvcSPName = '[dbo].[another_sp]'; 

但是,上述方法只適用於我們不使用[dbo].[another_sp]中的任何參數。

如果我們使用[dbo].[another_sp]參數:

exec [dbo].[exec_sp_with_try_catch] @pnvcSPName = '[dbo].[another_sp] @para = ''K'''; 

它引發以下錯誤:

Msg 50000, Level 16, State 2, Procedure exec_sp_with_try_catch, Line 30
The name '[dbo].[another_sp] @para = 'K'' is not a valid identifier.

爲什麼,以及如何糾正呢?

回答

0

試試這個:

CREATE PROCEDURE [dbo].[exec_sp_with_try_catch] 
@pnvcSPName NVARCHAR(100) , 
@para NVARCHAR(100) 
AS 
DECLARE @ErrorMessage NVARCHAR(4000); 
DECLARE @ErrorSeverity INT; 
DECLARE @ErrorState INT; 
BEGIN 

    BEGIN TRY 
     exec @pnvcSPName @para; 
    END TRY 
    BEGIN CATCH 
     SELECT @ErrorMessage = ERROR_MESSAGE(), 
       @ErrorSeverity = ERROR_SEVERITY(), 
       @ErrorState = ERROR_STATE(); 

     RAISERROR(@ErrorMessage, -- Message text. 
       @ErrorSeverity, -- Severity. 
       @ErrorState -- State. 
     ); 

     IF XACT_STATE() <> 0 
      ROLLBACK TRANSACTION; 
    END CATCH 

END; 

exec dbo.exec_sp_with_try_catch '[dbo].[another_sp]','K'; 
+0

它的工作原理。謝謝。 –

0

做這樣的

CREATE PROCEDURE [dbo].[exec_sp_with_try_catch] (@pnvcSPName NVARCHAR(100)) 
AS 
DECLARE @ErrorMessage NVARCHAR(4000); 
DECLARE @ErrorSeverity INT; 
DECLARE @ErrorState INT; 
BEGIN 

    BEGIN TRY 
     EXEC sys.sp_executesql @pnvcSPName; --pay attention on possible need of escaping ' char here 
    END TRY 
    BEGIN CATCH 
     SELECT @ErrorMessage = ERROR_MESSAGE(), 
       @ErrorSeverity = ERROR_SEVERITY(), 
       @ErrorState = ERROR_STATE(); 

     RAISERROR(@ErrorMessage, -- Message text. 
       @ErrorSeverity, -- Severity. 
       @ErrorState -- State. 
     ); 

     IF XACT_STATE() <> 0 
      ROLLBACK TRANSACTION; 
    END CATCH 

END;