I have a maintenance plan on my SQL 2008 box - I would like it to send an email address when (or if) it fails. I've set up database mail, and can send a test email..
How can I do this?
I have a maintenance plan on my SQL 2008 box - I would like it to send an email address when (or if) it fails. I've set up database mail, and can send a test email..
How can I do this?
Add an Execute SQL task to your maintenance plan that makes the call to sp_send_dbmail and connect the failure routes of any of your other tasks to this task.
We added am "Execute T-SQL Statement Task", which calls a stored procedure, with the name of the Maintenance Plan as a paramater:
EXEC server.schema.SP_SENDALERT 'plan.subplan';
In that stored procedure, we query back to the SYSJOBS and SYSJOBHISTORY for the plan to obtain the message for the last 'failure', which we then send to 'IT Support' as part of a send_dbmail (which is driven by a procedure that loop through unsent messages in the MESSAGING table), something along the lines of this:
CREATE PROCEDURE SP_SENDALERT (@plan VARCHAR(MAX))
AS
BEGIN
DECLARE @error VARCHAR(MAX)
SELECT TOP 1 @error = SJH.[MESSAGE]FROM MSDB.DBO.SYSJOBS SJ
LEFT JOIN MSDB.DBO.SYSJOBHISTORY SJH ON SJ.JOB_ID = SJH.JOB_ID
WHERE SJ.ENABLED = 1
AND SJH.RUN_STATUS = 0
AND SJ.[NAME] = @plan
ORDER BY SJH.RUN_DATE, RUN_TIME DESC
INSERT INTO database.schema.MESSAGING
(MESSAGE_TYPE, MESSAGE_SUBJECT, MESSAGE_BODY, RECIPIENTS, RECORD_ADDED)
VALUES (1, 'ERROR: ' + @plan, @error, 'itsupport@x.com', GETDATE())
END