concept message in category sql

appears as: The messages, message, messages, messages, message
SQL Server MVP Deep Dives Vol. 2

This is an excerpt from Manning's book SQL Server MVP Deep Dives Vol. 2.

It’s quick to run (21 seconds on my test database, which is 1.6 GB in size), far quicker than a full database restore would be. The messages returned indicate 5 pages were processed, as you’d expect.

I’m assuming you’re familiar with Service Broker terminology and objects so I won’t describe them. Our template will set up a direct communication between two instances using transport security with certificates. This means that the communication channel between SQL Servers will be encrypted, but the messages themselves won’t be. Look into implementing dialog security if there’s a need for message encryption.

Let’s take a look at the DBReceiver database on the DataReceiver side and the DBSender database on the DataSender side. First you’ll create the Service Broker support objects like the error table to store any errors that occur when receiving messages, a table to store your received messages that you can use to process them further, and an activation stored procedure that will run and receive messages when they arrive in the Service Broker queue (see the following listing).

Listing 3. Creating support objects in DBReceiver on the DataReceiver instance
USE DBReceiver GO -- enable service broker for our database ALTER DATABASE DBReceiver SET ENABLE_BROKER -- get the Service broker ID to use later SELECT service_broker_guid FROM sys.databases WHERE name = 'DBReceiver' -- returns 962FF4B4-428B-482D-A0A7-748F62D3C41C on my machine GO -- create the schema that holds service broker support objects CREATE SCHEMA DataTransfer -- create table to hold errors when receiving messages CREATE TABLE DataTransfer.ReceiveErrors ( ID BIGINT IDENTITY(1, 1) PRIMARY KEY, ErrorProcedure NVARCHAR(126) NOT NULL, ErrorLine INT NOT NULL, ErrorNumber INT NOT NULL, ErrorMessage NVARCHAR(MAX) NOT NULL, ErrorSeverity INT NOT NULL, ErrorState INT NOT NULL, TransferData XML NOT NULL, ErrorDate DATETIME NOT NULL DEFAULT GETDATE() ) -- create table to hold received messages CREATE TABLE DataTransfer.ReceivedMessages ( ID INT IDENTITY(1, 1) PRIMARY KEY, TableSchema NVARCHAR(128) not null, TableName NVARCHAR(128) NOT NULL, TransferedRows XML NOT NULL, DialogID UNIQUEIDENTIFIER NOT NULL, MsgSeqNum BIGINT NOT NULL, CreatedOn DATETIME NOT NULL DEFAULT GETDATE() ) -- stored procedure that writes the transferred data -- from the queue to the DataTransfer.ReceivedMessages table -- when the conversation ends those messages can be processed -- with another stored procedure GO CREATE PROCEDURE DataTransfer.spReceiveTransferredData AS BEGIN DECLARE @msgBody XML, @dlgId uniqueidentifier, @msgSeqNum bigint, @msgTypeName SYSNAME WHILE(1=1) BEGIN BEGIN TRANSACTION BEGIN TRY -- receive one message at a time ;RECEIVE top(1) @msgBody = message_body, @dlgId = conversation_handle, @msgSeqNum = message_sequence_number, @msgTypeName = message_type_name FROM DataTransfer.QueueDataTransferReceive -- exit when the whole queue has been processed IF @@ROWCOUNT = 0 BEGIN IF @@TRANCOUNT > 0 ROLLBACK; BREAK; END -- if we get the EndOfTransfer message we're closing -- the conversation IF @msgTypeName = N'//DataTransfer/EndOfTransfer' BEGIN END CONVERSATION @dlgId; /* Here a stored procedure can be ran that processes messages stored in the DataTransfer.ReceivedMessages table */ END ELSE BEGIN -- insert the message into the -- DataTransfer.ReceivedMessages table -- with a little XML querying magic INSERT INTO DataTransfer.ReceivedMessages (TableSchema, TableName, TransferedRows,DialogID, MsgSeqNum) SELECT T.c.value('@TableSchema', 'nvarchar(128)') as TableSchema, T.c.value('@TableName', 'nvarchar(128)') as TableName, T.c.query('./rows') as rowsXml, @dlgId, @msgSeqNum FROM @msgBody.nodes('/*') T(c) END IF @@TRANCOUNT > 0 COMMIT; END TRY BEGIN CATCH IF @@TRANCOUNT > 0 ROLLBACK; -- insert error into the ReceiveErrors table INSERT INTO DataTransfer.ReceiveErrors( ErrorProcedure, ErrorLine, ErrorNumber, ErrorMessage, ErrorSeverity, ErrorState, TransferData) SELECT ERROR_PROCEDURE(), ERROR_LINE(), ERROR_NUMBER(), ERROR_MESSAGE(), ERROR_SEVERITY(), ERROR_STATE(), @msgBody -- here you can add extra logging to the error log -- or email notifications, etc... END CATCH; END END

You’ve ended the conversation in the spReceiveTransferredData stored procedure by using the //DataTransfer/EndOfTransfer message type. This is to avoid a very common and very wrong pattern developers like to use called “fire and forget.” Here’s how this pattern works: you send a message from DataSender to DataReceiver and then end the conversation from the DataSender side. The problem with this is that any returned messages are lost to the DataSender because the conversation is already over as far as it’s concerned. That’s the reason you always have to end the conversation from the DataReceiver side. This way, the DataReceiver sends the end conversation message to the DataSender, the DataSender responds with an “Okay, let’s end this” message, and both close their ends of the conversation properly. Because the received messages are stored in a separate table, you can do whatever you want with them either when the conversation is over (look at the comment in the code in the spReceiveTransferredData stored procedure) or in some other scheduled job. Note that if you want to send the messages in order, they need to be sent on the same conversation. In any case, the way to end a conversation stays the same as just described.