Next week I am talking to a few of our early adopters about Service Broker - a great piece of technology that we introduce in SQL Server 2005 for asynchronous messaging. I like to start to learn a new technology by finding the simplest example that works. There are several fine examples out there - but nothing quite as simple as I would have liked. So I created my own. I should have plenty more to say on service broker next week - but for the moment - enjoy the simplicity :)

CREATE DATABASE TestSB
go
USE TestSB
go

-- SETUP: setup the infrastructure to send a message via service broker
-- Need a sender Q (TxQ) and receiver Q (RxQ)
CREATE QUEUE TxQ
CREATE QUEUE RxQ

-- Need a message type to send
CREATE MESSAGE TYPE Msg

-- Need a contract that says who can send the message type
CREATE CONTRACT MsgContract(Msg SENT BY ANY)

-- Need services to look after the Qs
CREATE SERVICE TxSvc ON QUEUE TxQ
CREATE SERVICE RxSvc ON QUEUE RxQ (MsgContract)

-- TEST IT: Run this in a SECOND Window to wait for a message on the destination q
WAITFOR (RECEIVE TOP(1)
  CAST(message_body as XML)      
   FROM RxQ);

-- TEST IT: Send one message - need to send as part of a dialog
DECLARE @h uniqueidentifier
BEGIN DIALOG CONVERSATION @h
 FROM SERVICE TxSvc TO SERVICE 'RxSvc'
 ON CONTRACT MsgContract;
 
 SEND ON CONVERSATION @h MESSAGE TYPE Msg ('<hello>world</hello>')
END CONVERSATION @h;