SQL代理作业失败时在电子邮件中生成错误完整消息

时间:2016-10-17 17:13:19

标签: sql sql-server-2012 sql-agent-job

我有3个执行SSIS包的SQL代理作业。当作业出错时,它会生成一封电子邮件,其中“作业失败 - '在主题和电子邮件中有一条消息'作业失败。该作业由计划schename调用,最后一步是运行_'

当我查看作业的历史记录时,它没有可见的FULL错误消息。是否有任何方法可以将作业配置为在电子邮件中包含COMPLETE错误消息?或者,有没有办法可以构建一个存储过程,该存储过程将在特定的作业失败时执行,并查询其中一个系统表(sysjobs)?

我之前从未这样做过,但我想我可以在sysjobs表中构建一个触发器,该触发器在特定作业失败后触发,并执行sp_db_sendmail。我试图避免走这条路。是否有完成任务的最佳方式?

2 个答案:

答案 0 :(得分:0)

一种更好的方法是使用多个作业步骤。

Step1: Execute Package

如果Step1失败:

Step2: use T-SQL with sp_db_sendmail

Step2可以通过多种方式进行自定义,例如可以附加上一步ssis包生成的日志。

或者

从作业历史记录中获取错误消息并添加到sp_db_sendmail Refer

如果您使用的是Project部署模型,则可以使用SP执行ssis包等目录,从日志表中获取错误详细信息。

答案 1 :(得分:0)

这是一个可以在作业中使用的脚本。它会查找当天失败的任何作业。您可以每天运行一次,以查看当天失败的工作。如果要每30分钟左右运行一次,并且只能查看过去一小时内失败的作业,则可以添加时间变量。您必须能够使用xp_cmdshell我认为您可以使用sp_send_dbmail

declare @filepath nvarchar(100)     --file path where results are stored as csv
declare @filename nvarchar(100)     --file name where results are stored
declare @command nvarchar(4000)     --dynamic sql of bcp command
declare @count int                  --result count
declare @emailList varchar(4000)    --people to email
declare @dt int                     --current date in INT format



set @filepath = '"e:\somefolder\'
set @filename = 'Failures.csv"'
set @emailList = 'email@domain.com; someOtherEmail@domain.com'
set @dt = (select convert(int,replace(convert(date,substring(convert(varchar,getdate()),1,11)),'-','')))

--query to get the jobs that failed and why. Looks for jobs that were executed today.
select
    h.run_date,
    h.run_time,
    h.run_status,
    j.name,
    j.description,
    h.message
from 
    msdb.dbo.sysjobhistory  h
    inner join
    msdb.dbo.sysjobs j on j.job_id = h.job_id
where
    h.run_status = 0
    and h.run_date = @dt

--if there were failures then put them in a csv and email them.
set @count = @@ROWCOUNT

if (select @count) > 0
begin
    set @command = 'bcp "select h.run_date, h.run_status, j.name, j.description, h.message from msdb.dbo.sysjobhistory h inner join msdb.dbo.sysjobs j on j.job_id = h.job_id where h.run_status = 0 and h.run_date = convert(int,''' + convert(varchar,@dt) + ''') " queryout '
    set @command = @command + @filepath + @filename + ' -c -t, -T '----> character data, tab delimtted is default use  -t, for comma ... trusted conn,server instance to connect to
    exec master..xp_cmdshell @command

    exec msdb.dbo.sp_send_dbmail 
                    @profile_name = null,
                    @recipients  = @emailList,
                    @body = 'Attached is the job failure results',  
                    @body_format = 'TEXT',
                    @subject = 'Job Failures',
                    @file_attachments = 'e:\someFolder\Failures.csv'

end