步骤失败时SQL作业的通知

问题描述 投票:0回答:1

尝试在sql作业上只有1(或更多)步骤失败时,找出是否有办法设置电子邮件通知。我有一个9个步骤的工作,但每个步骤都需要设置为继续下一步,即使它失败了。因此,即使步骤失败,因为我需要它进入下一步,它不会设置为“报告失败”。由于SQL Server代理没有“报告失败并转到下一步”的选项,我想知道是否有人有任何收到通知的方法

sql sql-server ssms sql-agent
1个回答
0
投票

您可以添加其他作业步骤来查询msdb表以查找失败的步骤。在此之后,sp_send_dbmail存储过程可用于发送包含错误的电子邮件(如果有)。 run_dateSYSJOBHISTORY列是一个int列,因此日期将沿着YYYYMMDD的格式。 run_status列下面的过滤器将适用于各个步骤,无论整体作业结果如何,0表示失败状态。

DECLARE @JobExecutionDate INT 

--current date
SET @JobExecutionDate = CAST(CONVERT(VARCHAR(8),GETDATE(),112) AS INT) 


--check if there were any errors first
IF EXISTS (SELECT h.instance_id
FROM MSDB.DBO.SYSJOBHISTORY h 
         INNER JOIN MSDB.DBO.SYSJOBS j ON h.job_id = j.job_id 
         INNER JOIN MSDB.DBO.SYSJOBSTEPS s ON j.job_id = s.job_id AND h.step_id = s.step_id
WHERE h.run_status = 0 AND h.run_date = @JobExecutionDate AND j.name = 'YourJobName')

BEGIN

DECLARE @Title VARCHAR(50)

SET @Title = CONCAT(CONVERT(VARCHAR(12), CAST(GETDATE() AS DATE), 109), ' Job Error Email')


EXEC msdb.dbo.sp_send_dbmail  
    @profile_name = 'Your Database Mail Profile',  
    @recipients = '[email protected]',  
@query = 'SELECT  j.[name] AS JobName,  
         s.step_name AS StepName,  
         h.run_date AS RunDate, 
         h.run_time AS RunTime, 
         h.sql_severity As ErrorSeverity, 
         h.message AS ErrorMessage
FROM MSDB.DBO.SYSJOBHISTORY h 
         INNER JOIN MSDB.DBO.SYSJOBS j ON h.job_id = j.job_id 
         INNER JOIN MSDB.DBO.SYSJOBSTEPS s ON j.job_id = s.job_id AND h.step_id = s.step_id
WHERE h.run_status = 0 AND h.run_date = CAST(CONVERT(VARCHAR(8),GETDATE(),112) AS INT) AND j.name = ''YourJobName''
',
  @query_result_no_padding = 1,
    @subject = @Title ;


END
© www.soinside.com 2019 - 2024. All rights reserved.