Working with Dialogs

With the Service Broker infrastructure created, messages can be sent between services and received from the queue. Messages exist as part of a conversation, and multiple conversations can be contained in a conversation group.

Service Broker makes multiple queue readers possible by locking the conversation group; however, locking the conversation group with normal database commands is almost impossible to accomplish efficiently. Service Broker accordingly uses a new kind of database lock, and only Service Broker commands understand this lock type.

Sending a Message to the Queue

The following code creates a conversation that is identified by a conversationhandle GUID. SEND places a single message onto a queue within a transaction. The BEGIN CONVERSATION command opens the conversation, and the SEND command actually places the message into the queue:

BEGIN TRANSACTION ; 

DECLARE @message XML ;
SET @message = N'<message>Hello, World!</message>’ ;

DECLARE @conversationHandle UNIQUEIDENTIFIER ;

BEGIN DIALOG CONVERSATION @conversationHandle
  FROM SERVICE [InitiatorService]
  TO SERVICE ‘TargetService'
  ON CONTRACT [HelloWorldContract]
  WITH ENCRYPTION = OFF, LIFETIME = 1000 ;

SEND ON CONVERSATION @conversationHandle
 MESSAGE TYPE [HelloWorldMessage]
 (@message) ;

END CONVERSATION @conversationHandle ;

COMMIT TRANSACTION ;

A queue is an internal table, but all you can do is SELECT or RECEIVE. You can't use any other command such as UPDATE or DELETE. To view the messages in ...

Get Microsoft SQL Server 2012 Bible now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.