Question

I'm going to run via a SQL Job a backup which will back up 4 databases. What I want to do is to be able to send an email via my Database Mail profile if any of the backup's fail.

Now I know there is a very obvious way of doing this on the job itself but my boss doesn't want it done like that.

What we want is within the T-SQL code for the job is to be able to detect the backup failing or the job itself failing and then send the email.

I hope I've explained the issue.

Thanks to everyone in advance who may have some ideas for me.

Nick

Was it helpful?

Solution

Give this a spin:

BEGIN TRY
BACKUP LOG @v_DatabaseName TO DISK = @v_BackupFileLocation WITH NAME = @v_BackupFileName, SKIP, STATS = 10
END TRY
BEGIN CATCH
Set @v_ErrorMailSubject = 'Transaction log backup failure in database '+@v_DatabaseName
Set @v_ErrorMailText = 'An error occured in transaction log backup for database '+@v_DatabaseName+'.'+Char(13)+Char(13)
Set @v_ErrorMailText = @v_ErrorMailText + 'Error '+Cast(Error_Number() as nvarchar)+' - ['+Error_Message()+']'
exec msdb.dbo.sp_send_dbmail    @recipients=@v_ErrorMailRecipient, 
                @subject = @v_ErrorMailSubject,
                @body = @v_ErrorMailText
END CATCH

You'll need to configure the database email configurations first, though

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top