递归过程错误处理

时间:2015-10-06 14:43:20

标签: sql sql-server

如何在递归过程中处理错误?我正在使用SQL Server 2012。

CREATE PROCEDURE [dbo].[TEST]
    @i INT
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;

    BEGIN TRANSACTION [T]
    BEGIN TRY

        PRINT @i

        IF @i = 10
        BEGIN
            COMMIT TRANSACTION [T]
            RETURN;
        END
        ELSE
        BEGIN
            SET @i = @i + 1;
            EXEC DBO.TEST @i;
        END

        COMMIT TRANSACTION [T]

    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT>0
            ROLLBACK TRANSACTION [T]
        SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
    END CATCH  

END

这只是一个例子,因为我没有自动发布原始代码。

1 个答案:

答案 0 :(得分:0)

CREATE PROCEDURE [dbo].[TEST]
    @i INT
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;

    DECLARE @InNestedTransaction BIT;

    BEGIN TRY

        IF (@@TRANCOUNT = 0)
        BEGIN
            SET @InNestedTransaction = 0;
            BEGIN TRAN; -- only start a transaction if not already in one
        END;
        ELSE
        BEGIN
            SET @InNestedTransaction = 1;
        END;

        /*********************************************/
        PRINT @i

        IF @i = 8
        BEGIN
            DECLARE @ForceError INT;
            --set @ForceError = 1/0; -- uncomment this line to force error.
        END
        IF @i = 10
        BEGIN
            RETURN;
        END
        ELSE
        BEGIN
            SET @i = @i + 1;
            EXEC DBO.TEST @i;
        END
        /*********************************************/

        IF (@@TRANCOUNT > 0 AND @InNestedTransaction = 0)
        BEGIN
           COMMIT;
        END;

    END TRY 
    BEGIN CATCH
        IF (@@TRANCOUNT > 0 AND @InNestedTransaction = 0)
        BEGIN
            ROLLBACK;
            SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage;
        END;
        ELSE
        BEGIN
            THROW;
        END

    END CATCH

END