2010年4月21日 星期三

SQL 2005 Job Mail 通知

SQL 2005後,提供了Database Mail的功能,可以利用SMTP MAIL設定JOB執行狀況的EMAIL通知

在SQL 2000的時代,未曾使用過SQL MAIL, 既然SQL 2005有了這麼方便的SMTP MAIL功能,那就來試看看, 因為主要是想要知道每天排程的JOB到底是成功還是失敗. 不然每次都等人客打電話來通知,實在是太沒面子了.

1.開啟SQL SERVER 2005 的Database Mail,
   sp_configure 'show advanced', 1;
   sp_configure 'Database Mail XPs', 1; 
   GO
   RECONFIGURE;
  GO
2.設定Database Mail, 可以使用SSMS->Management下的Database Mail以精靈的方式設定   MSSQLTip上有完整的說明及畫面   http://www.mssqltips.com/tip.asp?tip=1100,   如果要用SCRIPT新增,可以參考MSDN上的範例,我修改後如下
  -- Create a Database Mail account
  EXECUTE msdb.dbo.sysmail_add_account_sp
 @account_name = 'testAccount',
 @description = 'Mail account for test e-mail.',
 @email_address = 'test@mail.test.com',
 @replyto_address = null,
 @display_name = 'testMailer',
 @mailserver_name = 'mail.test.com' ;


 -- Create a Database Mail profile
 EXECUTE msdb.dbo.sysmail_add_profile_sp
 @profile_name = 'testProfile',
 @description = 'Profile used for test mail.' ;


 -- Add the account to the profile (一個profile可有多個account)
 EXECUTE msdb.dbo.sysmail_add_profileaccount_sp
 @profile_name = 'testProfile',
 @account_name = 'testAccount',
 @sequence_number =1 ;


 -- Grant access to the profile to the DBMailUsers role
 EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
 @principal_name = 'public',
 @profile_name = 'testProfile',
 @is_default = 1 ;
 
3.在SQL Server Agent 按右鍵選properties, 進入後在Alert System 下 勾選 Enable mail profile,挑選步驟2所設定的profile  name
4.在SQL Server  Agent 下,找到Operators目錄,按右鍵New operator, 在Name給這個operator指定一個名稱,在E-mail name 輸要發送的對象E-mail, 如果有多個就用;隔開,例如test1@mail.com.tw;test2@mail.com.tw, 以此類推
當然, 你可在此建立多個不同用途的operator, 以方不同性質的job針對不同管理者進行通知

5.最後是....記得重新啟動SQL Server Agent  服務....大功告成

做個測試....
建一個job, 隨便做一個會出錯的step, 例如讀一個不存在的table, select 1 from xxx

在job的Notification中, 勾選E-mail, 選擇步驟4所建立的Operator, 然後指定When the job fails , 這樣當step 執行有錯誤時,就會啟動送email的機制了.

如果以上通通沒搞錯, 試跑一下job, 就收到錯誤email通知了

JOB RUN: 'test' was run on 2010/4/21 at 下午 10:05:16

DURATION: 0 hours, 0 minutes, 0 seconds
STATUS: Failed
MESSAGES: The job failed. The Job was invoked by User win2003\Administrator. The last step to run was step 1 (test).

缺點是....錯誤訊息太精簡了, 也許就只是通知(notification) .

google了一下, 看看這篇文章, 自已想辦法去讀取sysjobstepslogs的完整錯誤吧

以後再試

沒有留言:

張貼留言

publish error allowDefinition='MachineToApplication'

一個老舊的aspx web form專案,調了一些功能建置成功,但進行部署時顯示以下錯誤。 在應用程式層級之外使用註冊為 allowDefinition='MachineToApplication' 的區段發生錯誤。錯誤的原因可能是虛擬目錄尚未在 IIS 中設定為...