MS SQL Server alerts and email operator notifications

  • Category: 電腦相關
  • Last Updated: Tuesday, 20 December 2016 23:37
  • Published: Monday, 22 August 2016 14:33
  • Written by sam

設定MSSQL排程工作通知功能

 photo 2016-08-22_134846_cr_zpsla2ahsyf.jpg

 photo 2016-08-22_134936_zps7jiaoemm.jpg

 photo 2016-08-22_134947_zpsfablx3xq.jpg

填入設定檔名稱(自訂)

 photo 2016-08-22_135001_zpsf4k2okqe.jpg

填入相關資訊,這邊是使用GMAIL來發信,所以SSL要打勾並填上PORT號587

最後下方的驗證記得填入

 photo 2016-08-22_135135_zpstcn0artu.jpg

再來回到上一步,此部份可有可無(主要是預設值寄出檔案為1MB,可以依需求修改)

 photo 2016-08-22_135149_zpsfhms0czi.jpg

我將預設值改為10MB

 photo 2016-08-22_135205_zpsodvpob0t.jpg

至此可以試發郵件,如無誤會收到信件

  photo 2016-08-22_135220_cr_zpstpsyqdcg.jpg

再來點擊 操作員 並新增

 photo 2016-08-22_135419_cr_zpselslgeew.jpg

填入自訂值

 photo 2016-08-22_135509_zpsrdwtizjt.jpg

點選SQL Server Agent

選用先前設定的帳號

 photo 2016-08-22_135614_zpsvpnbiyem.jpg

找一隻自訂的JOB測試

 photo 2016-08-22_135640_zpso5btcchg.jpg

 photo 2016-08-22_135711_cr_zpszq3fjarb.jpg

 在"通知"項目,可以見到要在何時通知,自訂即可

 photo 2016-08-22_135843_cr_zpsgaodfold.jpg

另外也附上直接在SQL執行完時,通知執行結果TSQL

EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'sam',
@recipients = 'sam小老鼠myla.gotdns.com',
@subject = 'SQLJOB24HRS-',
@query = 'Select 
        [Job Name] = CONVERT(NVARCHAR(50), j.name)
   , ROW_NUMBER() Over (Partition By j.name Order By h.run_time) as [SN]
      , [LastRunDate] = h.run_date
      , CONVERT(VARCHAR,DATEADD(S,(run_time/10000)*60*60 /* hours */
          +((run_time - (run_time/10000) * 10000)/100) * 60 /* mins */
          + (run_time - (run_time/100) * 100)  /* secs */
      , CONVERT(DATETIME,RTRIM(run_date),113)),120) AS [Time Run]
      , CONVERT(VARCHAR(10),CONVERT(DATETIME,RTRIM(19000101))+(h.run_duration * 9 + h.run_duration % 10000 * 6 + h.run_duration % 100 * 10) / 216e4,108) AS [Run_Duration]
      , CASE h.run_status
  when 0 then ''Failed''
  when 1 then ''Pass''
  when 2 then ''Retry''
  when 3 then ''Cancel''
  when 4 then ''Running''
 end as [JobStatus]
    From
        msdb.dbo.sysjobhistory h
      Left join msdb.dbo.sysjobs j On j.job_id = h.job_id
    Where h.step_id=0
    AND DATEADD(S,
  (run_time/10000)*60*60 /* hours */
  +((run_time - (run_time/10000) * 10000)/100) * 60 /* mins */
  + (run_time - (run_time/100) * 100)  /* secs */
  , CONVERT(DATETIME,RTRIM(run_date),113)) >= DATEADD(d,-1,GetDate()) ',
@attach_query_result_as_file = 1,
@query_attachment_filename = 'SQLJOB24HRS.TXT'

#######160827######

check notify

select name, notify_level_email, notify_email_operator_id
from msdb..sysjobs
order by name, notify_level_email

update notify setting

UPDATE S
SET S.[notify_level_email] = 2,
S.[notify_email_operator_id] = 1
FROM MSDB.dbo.sysjobs S
WHERE S.[Notify_Level_Email] = 0
AND S.[Enabled] = 1;
GO