views:

24

answers:

2

Hi,

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.

+2  A: 

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

SQLMenace
humm that is what i thought initially...however I thought it would be like a print statement...u know...shoot and forget kind of a thing because it is executing the proc....I even tried by putting the mail code outside the begin end but it still does not work....
Ved
A: 

You need to create a savepoint, attempt your operation, in case of error rollback to the savepoint, send the mail message then commit. Similar to the pattern described in Exception handling and nested transactions.

Remus Rusanu