如何在catch块中出错后继续?

时间:2016-08-23 07:39:19

标签: sql sql-server sql-server-2012 transactions

我需要循环浏览10条记录,并将这些记录插入到事务中的3个不同表中。我是从事务循环中一次记录的。

我的要求是,如果成功插入前8条记录,并且if语句在第9条记录失败,则应记录错误并继续插入第10条记录。

如果任何行有任何错误,则存储过程不应停止。

我尝试将事务放在子TRY-CATCH块中,但仍然失败。

BEGIN TRY

DECLARE  @TotalRecord          AS INT = 10
        ,@LoopStartCount       AS INT = 1
        ,@AskPkQuotationId     AS INT;     

--Some select stuff here       
WHILE(@LoopStartCount <= @TotalRecord)
BEGIN 

    BEGIN TRY
    BEGIN TRAN

    --Do some insert update for each record.

    COMMIT TRAN
    END TRY

    BEGIN CATCH

    --Log Error and Continue with next record

    END CATCH
     SET @LoopStartCount = @LoopStartCount + 1;
    END



END TRY
BEGIN CATCH
 --Log parent error
END CATCH

2 个答案:

答案 0 :(得分:3)

实现try ... catch仅限于While循环,而不是整个代码。我在这里给你一个示例演示。

DECLARE @I INT = 0
DECLARE @Table TABLE (
    ID INT identity(1, 1)
    ,c2 INT
    )

INSERT INTO @table (c2)
VALUES (1)
    ,(2)
    ,(0)
    ,(3)
    ,(4)

SELECT *
FROM @Table

WHILE @I < 5
BEGIN
    BEGIN TRY
        SET @I = @I + 1

        SELECT @I / (
                SELECT c2
                FROM @table
                WHERE ID = @I
                ) AS Quotient
    END TRY

    BEGIN CATCH
        SELECT ERROR_NUMBER() AS ErrorNumber
            ,ERROR_SEVERITY() AS ErrorSeverity
            ,ERROR_STATE() AS ErrorState
            ,ERROR_PROCEDURE() AS ErrorProcedure
            ,ERROR_LINE() AS ErrorLine
            ,ERROR_MESSAGE() AS ErrorMessage;
    END CATCH
END

此代码在第三行返回错误但仍继续处理直至结束。

答案 1 :(得分:0)

尝试以下内容。在catch部分,你可以处理这个场景。

BEGIN TRY

DECLARE  @TotalRecord          AS INT = 10
        ,@LoopStartCount       AS INT = 1
        ,@AskPkQuotationId     AS INT;     

--Some select stuff here       
WHILE(@LoopStartCount <= @TotalRecord)
BEGIN 

    BEGIN TRY
    BEGIN TRAN 

    --Do some insert update for each record.

    COMMIT TRAN
    END TRY

    BEGIN CATCH

    --Log Error and Continue with next record
    IF @@TRANCOUNT >1

    BEGIN
    INSERT INTO dbo.ERROR_DETAILS --INSERTING ErrorInfo INTO LOG TABLE
    SELECT
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_SEVERITY() AS ErrorSeverity,
        ERROR_STATE() AS ErrorState,
        ERROR_PROCEDURE() AS ErrorProcedure,
        ERROR_LINE() AS ErrorLine,
        ERROR_MESSAGE() AS ErrorMessage

    ROLLBACK TRAN 

    END
    GOTO LOOPCOUNTER1
    END CATCH
    LOOPCOUNTER1:
     SET @LoopStartCount = @LoopStartCount + 1;
    END
END

END TRY
BEGIN CATCH
 --Log parent error
END CATCH