我很抱歉这是重复。我找不到符合我要求的问题。(这类似于我如何在存储过程中创建带有 RAISERROR 的参数?)
我在 SQL Server 代理中有一个非常简单的工作,只需一步。该包只执行一个存储过程。存储过程有一个 try / catch 块,当我尝试引发异常时,它会被捕获但不会向上传播并导致作业报告错误。作业成功。我将错误记录到本地表中并提交它,所以我知道我确实进入了 catch 块。我尝试过使用严重级别 16 和 20 以及其他一些可能不值得一提的东西来引发错误。
这是导致它无法传播的包设置还是我的存储过程有问题?谢谢。
-- dumbed down structure
BEGIN
SET NOCOUNT ON;
-- buncha vars
BEGIN TRY
BEGIN TRANSACTION
set @StepNumber = 10;
select 1/0;
COMMIT TRANSACTION;
RETURN 0;
END TRY
BEGIN CATCH
-- get the error
SELECT @ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE();
-- rollback the transaction
ROLLBACK TRANSACTION;
-- log the caught exception into the local log
set @LogTimestamp = GETUTCDATE();
set @LogMessage = @SessionGUID + ' - ' + CAST(@StepNumber AS NVARCHAR) + ' - ' + ' ERROR - ENTERED CATCH BLOCK - ERROR_MESSAGE()=' + @ErrorMessage + ' ERROR_SEVERITY()=' + cast(@ErrorSeverity as nvarchar) + ' ERROR_STATE()=' + CAST(@ErrorState as nvarchar) ;
insert into @LocalLog(TimestampDT, SourceVch, MessageVch) values (@LogTimestamp, @LogSource, @LogMessage);
-- transfer local log to master log table
BEGIN TRANSACTION;
--insert into RealTable selecting from @LocalLog;
COMMIT TRANSACTION;
-- slightly modify the error message before raising it to parent process
SET @ErrorMessage = @LogSource + ' - error with @StepNumber=[' +CAST(@StepNumber as nvarchar)+ '] ERROR_MESSAGE()=' + @ErrorMessage;
-- rethrow the error to the calling process
RAISERROR (@ErrorMessage, @ErrorSeverity, @ErrorState);
-- do we need this return?
RETURN @StepNumber;
END CATCH
END
我得到的日志表告诉我我至少发现了错误(来自我的日志表)。“6a3e80fd-f480-459c-a42f-25fd3d5a42a8 - 125 - 错误 - 输入捕获块 - ERROR_MESSAGE()=除以零错误。ERROR_SEVERITY()=16 ERROR_STATE()=1”