How do you use the END CONVERSATION statement to end a conversation in Service Broker?
Posted by DavidLee
Last Updated: June 12, 2024
In SQL Server's Service Broker, the END CONVERSATION statement is used to mark a dialog as complete. This is an important part of managing conversations in Service Broker, as it helps to ensure that resources associated with the dialog are cleaned up and that the conversation state is properly maintained. Here's how you can use the END CONVERSATION statement:
Syntax
END CONVERSATION conversation_handle
   [WITH CLEANUP | WITHOUT CLEANUP]
- conversation_handle: This is a required parameter that specifies the unique identifier of the conversation you want to end. It is typically obtained from a previous message or query. - WITH CLEANUP: This optional clause allows for the immediate cleanup of resources associated with the conversation. - WITHOUT CLEANUP: This optional clause allows the conversation to remain in the state of "ended" but does not free the resources immediately.
Example
Here’s an example of how to end a conversation in Service Broker: 1. Sending a message (initiating a conversation): First, you would typically start a conversation and send a message. For example:
DECLARE @conversation_handle UNIQUEIDENTIFIER;

   BEGIN DIALOG CONVERSATION @conversation_handle
       FROM SERVICE [SenderService]
       TO SERVICE 'ReceiverService'
       ON CONTRACT [YourContract]
       WITH ENCRYPTION = OFF;

   SEND ON CONVERSATION @conversation_handle
       MESSAGE TYPE [YourMessageType]
       ('Your message content');
2. Ending the conversation after processing: After the receiver processes the message, you would then end the conversation like this:
END CONVERSATION @conversation_handle WITH CLEANUP;
Points to Remember
- Ending a conversation marks it as complete, and no further messages can be sent on that dialog. - Using WITH CLEANUP will free up the resources immediately. If you omit it or specify WITHOUT CLEANUP, the dialog is still ended, but resources might remain allocated until a later cleanup operation occurs. - It’s important to manage conversations properly to avoid resource leaks in the database.
Checking for Active Dialogs
You can check the status of active dialogs and their recent activity using:
SELECT * FROM sys.conversation_endpoints;
This query can help you determine which conversations are still active or have been ended, along with their statuses. By following these steps and understanding this functionality, you can effectively manage conversations within SQL Server's Service Broker.