我有以下存储过程语句:
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}}被忽略了。
为什么会这样?
答案 0 :(得分:0)
@FailedRecord总是返回空 - 第二次捕获总是返回错误“将数据类型varchar转换为bigint时出错。”
使用convert / cast you BigInt
SET @FailedRecord = @FailedRecord +','+ Cast(@CurrentId as VARCHAR(20))
1st Try / Catch仅在(或错误转换:))
中起作用INSERT INTO #tmpNewApp SELECT Id,电子邮件,内容来自dbo.NewApplication
在第二次Catch或测试值上将insert插入DatabaseException并在变量
中存储错误消息 IF @FailedRecord <> ''