How can i create out parameters with RAISERROR in stored procedure?

╄→尐↘猪︶ㄣ 提交于 2019-12-10 11:37:26

问题


How can i create out parameters with RAISERROR in MSSQL?

This id stored procedure for example:

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:


If i understand your question you can create a SP that return the errors so:

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;

and to execute the SP and check the error:

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


来源:https://stackoverflow.com/questions/10764287/how-can-i-create-out-parameters-with-raiserror-in-stored-procedure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!