I have a stored procedure that I currently manually run whenever a user needs me to. I am developing an interface for them to be able to kick it off themselves. I've got it up and running using SQL Service Broker to queue the users' call to the stored procedure.
It works if I remove the call, near the end of the stored procedure, to sp_send_dbmail. Otherwise, with the call left in, it creates a block against itself and hangs indefinitely (does not happen when I run it manually).
When I kill the process that is blocked (I'm guessing this is the query within the call to dbmail), the email is sent but does not include any results.
What is going on and how do I fix it?
Here is a rough idea of how the stored procedure is calling dbmail, and what the blocking/blocked processes look like that I have to mess with to get it to "complete":
use mydb
declare @filename char(24)
set @filename = 'Results' + convert(char(10),convert(date,getdate())) + '.csv'
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'AnonMailProfile',
@recipients = 'me@myemail.com',
@query = '
select a,b,c
into #tmpTable
from
(select a,b,c
from mydb..TableA
left join mydb..TableB
on KeyA = FKeyA
union all
select a,b,c
from mydb..TableA
left join mydb..TableC
on KeyA = FKeyA
) as ct
;with cte as(
select *,rn = ROW_NUMBER() over (partition by something order by something)
from #tmpTable
)
select * from cte
',
@subject = 'Process Complete',
@attach_query_result_as_file = 1 ,
@query_attachment_filename = @filename,
@query_result_no_padding = 1,
@query_result_separator = ' ';
| SPID | Status | Login | HostName | BlkBy | DBName | Command | ProgramName | |------|------------|-------------|------------|-------|--------|-------------|-------------| | 36 | BACKGROUND | sa | . | . | master | EXECUTE | | | 66 | SUSPENDED | DS\USER | servername | 36 | master | SELECT INTO | SQLCMD |