2012-05-26 78 views
1

我如何在MSSQL中用RAISERROR創建參數?如何在存儲過程中使用RAISERROR創建參數?

例如

此ID存儲過程:

BEGIN TRY 

//OPERATION 

END TRY 
BEGIN CATCH 
    DECLARE @ErrorMessage NVARCHAR(4000); 
    DECLARE @ErrorSeverity INT; 
    DECLARE @ErrorState INT; 

    SELECT 
     @ErrorMessage = ERROR_MESSAGE(), 
     @ErrorSeverity = ERROR_SEVERITY(), 
     @ErrorState = ERROR_STATE(); 

    -- Use RAISERROR inside the CATCH block to return error 
    -- information about the original error that caused 
    -- execution to jump to the CATCH block. 
    RAISERROR (@ErrorMessage, -- Message text. 
       @ErrorSeverity, -- Severity. 
       @ErrorState -- State. 
       ); 
END CATCH; 

回答

1

如果我明白你的問題,你可以創建一個返回的錯誤,這樣一個SP:

CREATE PROCEDURE [dbo].[mySp] 
(
    @ErrorMessage NVARCHAR(4000) output = ''; 
    @ErrorSeverity INT output = 0; 
    @ErrorState INT output = 0; 
) 
AS 

BEGIN TRY 
-- OPERATION 
END TRY 
BEGIN CATCH 

    SELECT 
     @ErrorMessage = ERROR_MESSAGE(), 
     @ErrorSeverity = ERROR_SEVERITY(), 
     @ErrorState = ERROR_STATE(); 

END CATCH; 

和要執行的SP,並檢查錯誤:

DECLARE @ErrorMessage NVARCHAR(4000); 
DECLARE @ErrorSeverity INT; 
DECLARE @ErrorState INT; 

EXEC mySp (@ErrorMessage output, @ErrorSeverity output, @ErrorState output); 

if len(@ErrorMessage) > 0 
BEGIN 
    -- an error occur 
    select @ErrorMessage, @ErrorSeverity, @ErrorState; 

    -- or you can use the RAISERROR 
    RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState); 
END 
ELSE 
BEGIN 
    print 'OK'; 
END 
相關問題