Search code examples
sqlsql-serversql-server-2005sp-send-dbmaildbmail

send dbmail on @@error from sql server 2005


I am trying to send database mail when error occurs inside the transaction.My setup for dbo.sp_send_dbmail is correct , when I execute the proc I do get an email within 1 min.

However when I try to use dbo.sp_send_dbmail inside another proc within transactions than I do not get the email. Sql server does show in the result window that "Mail queued" but I never receive it.

BEGIN TRANSACTION

DECLARE @err int DECLARE @test nvarchar(max)

RAISERROR('This is a test', 16, 1) SELECT @err = @@ERROR

IF @err <> 0 BEGIN

SET @test = error_message()

EXEC msdb.dbo.sp_send_dbmail
@recipients= '[email protected]',
@body = 'test inside',
@subject = 'Error with proc',
@body_format = 'HTML',
@append_query_error = 1,
@profile_name ='Database Mail Profile';

ROLLBACK TRANSACTION RETURN END

COMMIT TRANSACTION

And I get result as

Msg 50000, Level 16, State 1, Line 7
This is a test
Mail queued.


Solution

  • You rolled it back so it never went out, put the email code outside the transaction

    From books on line

    When executing sp_send_dbmail from within an existing transaction, Database Mail relies on the user to either commit or roll back any changes. It does not start an inner transaction.

    http://msdn.microsoft.com/en-us/library/ms190307.aspx