Serge
Serge

Reputation: 4036

Service Broker messages inside a transaction

I am writing a stored procedure that would perform the following operations:

  1. BEGIN a transaction
  2. perform some tasks
  3. use Service Broker to kick-off a background process
  4. wait for a response message (with job status) from Service Broker
  5. COMMIT or ROLLBACK transaction, depending on the response message

The issue is that Service Broker communication is not working inside a TRANSACTION:

Here's an extract of my code:

-- Comment out the following line to make everything work
begin tran t1

DECLARE @Update_Msg XML([sb].[Service_Broker_xxx_Schemas]) = '
<Request xmlns="xxx">
  <Table xmlns="xxx">
    <Fields>
      xxx
    </Fields>
  </Table>
  <Requested_By>xxx</Requested_By>
</Request>'

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 > 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

What is the correct way to implement Service Broker messaging inside a transaction?

Upvotes: 2

Views: 1930

Answers (1)

Ben Thul
Ben Thul

Reputation: 32737

Sending messages via Service Broker is transactional. That is, if you do begin tran; send;, the message isn't actually sent until you commit.

Upvotes: 7

Related Questions