我怎样才能创造出与存储过程中RAISERROR参数?(How can i create out pa

2019-09-17 13:29发布

我怎样才能创造出与MSSQL 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;

Answer 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


文章来源: How can i create out parameters with RAISERROR in stored procedure?