USE SQL2008SBS
GO

DECLARE @handle         UNIQUEIDENTIFIER,
        @submitorder    XML,
        @order          XML,
        @messagetype    SYSNAME,
        @rc             INT --proc return code
        
BEGIN TRANSACTION

WHILE 1 = 1
BEGIN
    --Receive 1 message off the top of the queue
    WAITFOR(
    RECEIVE TOP(1) @handle = conversation_handle,
        @submitorder = message_body,
        @messagetype = message_type_name
    FROM OrderSubmitQueue), TIMEOUT 500;
    
    --Check for errors
    IF @@ROWCOUNT <> 0
    BEGIN
        IF @messagetype = 'http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog' 
            OR @messagetype = 'http://schemas.microsoft.com/SQL/ServiceBroker/Error'
        BEGIN
            END CONVERSATION @handle; 
        END
    
        --Execute proc to shred the order and write to tables
        EXEC @rc = dbo.asp_processpartnerorders @submitorder, @order OUTPUT;
        
        --Return the order to the queue for acknowledgement to the customer
        IF @rc = -1
        BEGIN
            SEND ON CONVERSATION @handle
            MESSAGE TYPE [//SQL2008SBS/Partner/AcceptedOrders]
            (@submitorder);
            
            END CONVERSATION @handle;
        END
        ELSE
        BEGIN        
            SEND ON CONVERSATION @handle
            MESSAGE TYPE [//SQL2008SBS/Partner/AcceptedOrders]
            (@order);
            
            END CONVERSATION @handle;
        END
    END
    ELSE
    BEGIN
        --Close any open transactions and break out of the loop
        WHILE @@TRANCOUNT > 0
        BEGIN
            COMMIT TRANSACTION
        END
        BREAK
    END
    
    --Make sure all open transactions are closed
    WHILE @@TRANCOUNT > 0
    BEGIN
        COMMIT TRANSACTION
    END
END
GO

--View results
SELECT OrderID, CustomerID, OrderDate, SubTotal, TaxAmount, ShippingAmount, 
    GrandTotal, FinalShipDate
FROM Orders.OrderHeader

SELECT OrderDetailID, OrderID, SKU, Quantity, UnitPrice, ShipDate
FROM Orders.OrderDetail

SELECT PartnerOrder
FROM Orders.InvalidOrders