How do you use the CREATE CONTRACT statement to create a new contract for Service Broker?
Posted by MaryJns
Last Updated: July 14, 2024
In SQL Server, the CREATE CONTRACT statement is used to define a contract for Service Broker, which specifies the message types that can be sent in a dialog between two services. A contract is essential for establishing the rules for communication. Here is the general syntax for using the CREATE CONTRACT statement:
CREATE CONTRACT contract_name
    [ ( message_type_name [ SENT BY { SERVICE | CONTRACT_OWNER } ] [ , ... ] ) ]
    [;]
Parameters:
- contract_name: The name of the contract you want to create. - message_type_name: The name of the message type that you want to be associated with this contract. - SENT BY { SERVICE | CONTRACT_OWNER }: Specifies who can send messages of the specified message type. It can either be a service (indicating that the service defined in the contract can send messages of the specified type) or the contract owner.
Example:
1. First, you need to create the message types that your contract will use.
CREATE MESSAGE TYPE [YourMessageTypeName]
    VALIDATION = NONE;
2. Then, you can create a contract that specifies which message types can be used.
CREATE CONTRACT [YourContractName]
    ([YourMessageTypeName] SENT BY SERVICE);
Complete Example:
Here's a complete flow to create a Service Broker contract:
-- Create a message type
CREATE MESSAGE TYPE [OrderMessage]
    VALIDATION = NONE;

-- Create a contract
CREATE CONTRACT [OrderContract]
    ([OrderMessage] SENT BY SERVICE);
Important Notes:
- Contracts are linked to services, and they define the conversation that can take place between them. - Once a contract is created, you cannot change its definition; you will need to drop it and recreate it if you need modifications. - Always ensure that you're following best practices for naming conventions to avoid confusion. After creating the contract, you can use it while establishing conversations between services in Service Broker.