title: Service Broker messages inside a transaction
body: <p>I am writing a stored procedure that would perform the following operations:</p>
  
  <ol>
  <li>BEGIN a transaction</li>
  <li>perform some tasks</li>
  <li>use Service Broker to kick-off a background process</li>
  <li>wait for a response message (with job status) from Service Broker</li>
  <li>COMMIT or ROLLBACK transaction, depending on the response message</li>
  </ol>
  
  <p>The issue is that Service Broker communication is not working inside a <code>TRANSACTION</code>:</p>
  
  <ul>
  <li>the message queue has activation enabled, but the associated stored procedure is <strong>not</strong> executed (<code>PRINT</code> statements in the stored procedure are not written to ERRORLOG file)</li>
  <li><code>RECEIVE</code> command times out</li>
  </ul>
  
  <p>Here's an extract of my code:</p>
  
  <pre><code>-- Comment out the following line to make everything work
  begin tran t1
  
  DECLARE @Update_Msg XML([sb].[Service_Broker_xxx_Schemas]) = '
  &lt;Request xmlns="xxx"&gt;
    &lt;Table xmlns="xxx"&gt;
      &lt;Fields&gt;
        xxx
      &lt;/Fields&gt;
    &lt;/Table&gt;
    &lt;Requested_By&gt;xxx&lt;/Requested_By&gt;
  &lt;/Request&gt;'
  
  DECLARE @conversation_handle UNIQUEIDENTIFIER
              ,@message_body varbinary(max)
              ,@message_type_name nvarchar(256)
              ,@timestamp datetime2
  
          BEGIN DIALOG CONVERSATION @conversation_handle
          FROM SERVICE [xxx_Initiating_Service]
          TO SERVICE 'xxx_Target_Service'
          ON CONTRACT xxx_Contract
          WITH ENCRYPTION = OFF;
  
          SEND ON CONVERSATION @conversation_handle
          MESSAGE TYPE [xxx_Command](@Update_Msg);
  
  
  select * from sys.transmission_queue with(nolock)
  --PRINT @conversation_handle
  
  WAITFOR (
      -- just handle one message at a time
      RECEIVE TOP(1)   @conversation_handle = conversation_handle     -- the identifier of the dialog this message was received on
                      ,@message_type_name = message_type_name
                      ,@message_body=message_body                     -- the message contents
                      ,@timestamp = GETDATE()
                      FROM [sb].[xxx_Initiator_Queue]
                      WHERE conversation_handle = @conversation_handle
  ), TIMEOUT 1000  -- if the queue is empty for one second, give UPDATE and go away
  IF @@ROWCOUNT &gt; 0
  BEGIN
          SELECT @@ROWCOUNT, @message_type_name, CONVERT(XML, @message_body)
          END CONVERSATION @conversation_handle;
  END
  ELSE
  BEGIN
      PRINT 'Did not receive any response from Service Broker.'
  END
  
  -- Comment out the following line to make everything work
  commit tran t1
  </code></pre>
  
  <p>What is the correct way to implement Service Broker messaging inside a transaction?</p>