USE SodaDB
GO

DROP PROCEDURE inventory_response
GO

CREATE PROCEDURE inventory_response
AS
DECLARE @c UNIQUEIDENTIFIER;
DECLARE @h UNIQUEIDENTIFIER;
DECLARE @m XML;
DECLARE @t NVARCHAR(128);

WHILE 1 = 1
BEGIN

BEGIN TRANSACTION
WAITFOR(
   GET CONVERSATION GROUP @c FROM InvResponseQueue_L8A),
   TIMEOUT 100 ;

IF @c IS NULL 
  BEGIN
   ROLLBACK TRANSACTION;
   BREAK;
  END

WHILE 1 = 1
BEGIN
	RECEIVE TOP(1) 
        @h=conversation_handle, 
        @t=message_type_name,
		@m=CAST(message_body as XML) FROM InvResponseQueue_L8A 
     WHERE conversation_group_id = @c;

    IF @@rowcount <> 1 
		BREAK;
    IF @t = N'http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog'
    OR @t = N'http://schemas.microsoft.com/SQL/ServiceBroker/Error' 
    BEGIN 
		END CONVERSATION @h;
        CONTINUE
    END

END
COMMIT TRANSACTION;
END
go

ALTER QUEUE InvResponseQueue_L8A WITH ACTIVATION 
  (STATUS=ON,
   PROCEDURE_NAME=inventory_response,
   MAX_QUEUE_READERS=5,
   EXECUTE AS SELF
  )
go