如何在所有SQL作业上添加操作员和电子邮件通知?

时间:2018-12-02 23:24:33

标签: sql-server ssms

要更主动地响应工作问题或失败,我想设置一个警报,添加一个操作员,并在工作失败时向我发送通知。我知道可以通过SSMS GUI添加操作员和通知,但这是一个非常耗时的过程,并且容易出错,因此我尝试通过脚本来实现。 以下脚本为我提供了工作:

USE msdb
SELECT sj.name AS JobName,
    CASE
    WHEN sj.enabled = 1 THEN 'Enable'
    ELSE 'Disable'
    END AS JobStatus,
    sj.description AS JobDescription,
    ss.name AS JobScheduleName,
    CASE
    WHEN ss.enabled = 1 THEN 'Enable'
    WHEN ss.enabled = 0 THEN 'Disable'
    ELSE 'Not Schedule'
    END AS JobScheduleStatus, 
    --ss.active_start_date AS ActiveStartDate,
    --ss.active_end_date AS ActiveEndDate,
    --ss.active_start_time AS ActiveStartTime,
    --ss.active_end_time AS ActiveEndTime,
    sh.step_name AS StepName,
    Case 
       sh.run_status WHEN 0 THEN 'Failed'
       WHEN 1 THEN 'Success'
       WHEN 2 THEN 'Retry'
       WHEN 3 THEN 'Canceled'
       WHEN 4 THEN 'In Progress' END AS Status,
    dbo.agent_datetime(run_date, run_time) As Last_Run_DateTime,
    sh.run_duration AS RunDuration,
     ((run_duration/10000*3600 + (run_duration/100)%100*60 + run_duration%100 + 31) / 60) as 'RunDurationMinutes'
FROM dbo.sysjobs AS sj
LEFT JOIN dbo.sysjobschedules AS sjs ON sj.job_id = sjs.job_id
LEFT JOIN dbo.sysschedules AS ss ON sjs.schedule_id = ss.schedule_id
LEFT JOIN dbo.sysjobhistory AS sh ON sj.job_id = sh.job_id

我也尝试添加运算符,如果我做错了,请纠正我。

DECLARE @Operator varchar(50)
SET @Operator = 'Emamr'
SELECT  sj.job_id AS JobID,
        sj.name AS JobName,
        sj.description AS JobDescription,
        ----adding operator using SP----
       'EXEC sp_update_job @job_name = ''' + sj.[name] + 
       ''', @notify_email_operator_name = ''' + @Operator  +
       ''', @notify_level_email = 2' As OperatorAdded  -- 1 = On Success, 2 = On Failure,3=always
FROM dbo.sysjobs sj
WHERE sj.enabled = 1 
AND sj.notify_level_email <> 1

添加运算符后,我需要设置一封电子邮件通知,但我不知道如何在一个脚本中执行此操作。任何帮助或指导将不胜感激

1 个答案:

答案 0 :(得分:1)

我会自己用powershell做到这一点:

import-module sqlps;
$s = 'someServerName'
$operator = @{Name = 'foo'; EMail = 'foo@bar.com'};

# no changes necessary below here

$serv = new-object Microsoft.SqlServer.Management.Smo.Server $s;
$js = $serv.JobServer;
$opers = $js.Operators;
if ( $opers -eq $null -or $opers[$operator.Name] -eq $null ) {
    $oper = new-object Microsoft.SqlServer.Management.Smo.Agent.Operator( $js, $operator.Name);
    $oper.EmailAddress = $operator.EMail;
    $oper.Create();
}

$jobs = $js.Jobs
foreach ( $job in $jobs ) {
    $job.OperatorToEmail = $Operator.Name;
    $job.EmailLevel = 'OnFailure';
    $job.Alter();
}