今天,我遇到了一个问题,即必须在作业中同时从其他存储过程和PHP api调用手动调用存储过程。后者使用sp的返回码确定成功,而前者仅将设置的错误级别理解为失败。
为了使问题进一步复杂化,我不得不将sp封装在try/catch中,因为必须发送电子邮件,并且需要在发生错误的情况下进行清理,即使在作业调度程序失败的情况下,sp也会成功报告。
看到THROW
和RETURN
都立即停止执行时,我如何进行设计以警告两个系统失败?
示例1-不抛出:
-- in catch block at end of sp
RETURN 1; -- execution stops here
THROW; -- throw back original error
示例2-不返回1:-- in catch block at end of sp
THROW; -- severity level is over 10, execution stops here
RETURN 1;
最佳答案
答案是使用RAISERROR
(否则不建议使用-as per MSDN documentation,“新应用程序应改为使用THROW
。”)。原因是因为严重性级别10以下的错误不会导致执行停止或跳转到当前的catch块,它只是设置@@ERROR
,但是THROW
不允许您设置错误严重性-it either uses 16 or the severity of the original error。
这样,这样的代码将设置错误级别并返回整数:
-- inside the stored procedure
BEGIN TRY
-- code
END TRY
BEGIN CATCH
-- do cleanup
-- code
-- send e-mail about error
-- code
-- this is the important part for us
DECLARE @msg NVARCHAR(MAX) = 'ERROR ' + CONVERT(NVARCHAR, ERROR_NUMBER()) + ': ' + ERROR_MESSAGE();
-- 5 is under the thresold of 10, and with @msg we preserve info about the original error
RAISERROR(@msg, 5, 0);
RETURN 1;
END CATCH
关于tsql - SQL Server-在使用返回码指示存储过程中的状态时,如何向作业调度程序发出故障信号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65564531/