I have a strange issue with msdb.dbo.sp_send_dbmail
within a stored procedure (code simplified):
SET NOCOUNT ON;
SET XACT_ABORT ON;
-- ...
SET @msg = N'...';
SET @filename = N'...';
EXEC msdb.dbo.sp_send_dbmail
@recipients = 'mailaddr@example.com'
, @blind_copy_recipients = 'another_mailaddr@example.com'
, @from_address = 'senders_mail@example.com'
, @subject = N'...'
, @body = @msg
, @query = N'SET NOCOUNT ON; SELECT <something> FROM <a_view>;'
, @execute_query_database = N'<same database the proc resides in>'
, @query_result_width = 8000
, @attach_query_result_as_file = 1
, @query_attachment_filename = @filename
, @query_result_header = 1
, @query_result_separator = ';'
, @query_result_no_padding = 1
, @exclude_query_output = 1;
I have a database user which is member of db_datareader
and EXECUTE
permissions for the stored procedure. Furthermore the assigned server login is mapped to msdb
and a member of the DatabaseMailUserRole
. There is only 1 single mail profile which is public
and flagged as default
.
Everything works fine from SSMS: connect with the user's credentials and execute the stored procedure. Great!
The first oddity: if I'm logged in as sysadmin
and try to EXECUTE AS
it doesn't work. Okay, I found something that points out that there are issues with this.
But the main issue is this: I call the procedure from a 3rd party Java application which connects using the jTDS driver (don't know if this is important). The applicaton executes the procedure ... and nothing else happened (no log entries, the task freezes).
In the activity monitor I see the following:
master
(??? I've never connected to this
db!)PREEMPTIVE_OS_GETPROCADDRESS
1
To make things worse I cannot kill this process. If I try this the Command column in the activity monitor shows only KILLED/ROLLBACK
.
KILL <PROCESS-ID>
shows
spid <...>: Transaction rollback in progress. Estimated rollback completion: 0% Estimated time left: 0 seconds.
I have to restart the whole instance to get rid of the process.
What is happening here?
Finally I found the answer here: blocking from xp_sysmail_format_query waittype of preemptive_os_getprocaddress
It seems that the Java application opens a transaction explicitly (there are 2 calls to stored procedures consecutively). After setting the Auto-Commit option of the database adapter to on
everything work's fine.