TSQL:嵌套的Try-Catch不捕获内部catch

时间:2017-11-06 08:05:39

标签: tsql stored-procedures sql-server-2014

我有以下存储过程语句:

DECLARE @CurrentId BIGINT
DECLARE @FailedRecord NVARCHAR(MAX) = ''

BEGIN TRY -- 1st Try
    INSERT INTO #tmpNewApp
        SELECT Id, Email, Content 
        FROM dbo.NewApplication

    WHILE EXISTS(SELECT * FROM #tmpNewApp)
    BEGIN
        BEGIN TRY -- 2nd Try
            SET @CurrentId = (SELECT TOP 1 Id FROM #tmpNewApp)

            INSERT INTO EmailSending
                SELECT Email, Content 
                FROM #tmpNewApp 
                WHERE Id = @CurrentId
        END TRY
        BEGIN CATCH -- 2nd Catch
            SET @FailedRecord = @FailedRecord + ', ' + @CurrentId;
        END CATCH

        DELETE FROM #tmpNewApp 
        WHERE Id = @CurrentId
    END
END TRY
BEGIN CATCH -- 1st Catch
    INSERT INTO DatabaseException
    SELECT ERROR_MESSAGE(), GETDATE()
END CATCH

SELECT @FailedRecord

我试图获取在循环期间遇到异常的ID列表。但是,@FailedRecord始终返回空,DatabaseException始终能够捕获异常,这似乎是第一个CATCH捕获的第二个CATCH和第二个CATCH中的语句{1}}被忽略了。

为什么会这样?

1 个答案:

答案 0 :(得分:0)

@FailedRecord总是返回空 - 第二次捕获总是返回错误“将数据类型varchar转换为bigint时出错。”

  1. 使用convert / cast you BigInt

    SET @FailedRecord = @FailedRecord +','+ Cast(@CurrentId as VARCHAR(20))

  2. 1st Try / Catch仅在(或错误转换:))

    中起作用

    INSERT INTO #tmpNewApp SELECT Id,电子邮件,内容来自dbo.NewApplication

  3. 在第二次Catch或测试值上将insert插入DatabaseException并在变量

    中存储错误消息
     IF @FailedRecord <> ''