Answered no message error prevention

  • Saturday, November 17, 2012 6:19 PM
     
     

    I am using the following code to check whether a message exists on the specified queue:

     

    Code Block

    DECLARE @RecvReplyMsg NVARCHAR(100);

    DECLARE @RecvReplyDlgHandle UNIQUEIDENTIFIER;

    BEGIN TRANSACTION;

    RECEIVE TOP(1)

    @RecvReplyDlgHandle = conversation_handle,

    @RecvReplyMsg = message_body

    FROM TargetQueue;

    END CONVERSATION @RecvReplyDlgHandle;

    SELECT @RecvReplyMsg AS ReceivedReplyMsg;

    COMMIT TRANSACTION;

    GO

     

     

    How can I prevent errors being thrown when there are no messages waiting on the queue? For example, if I send a message to the queue and run the above twice I get the following:

     

    Msg 8418, Level 16, State 1, Line 11

    The conversation handle is missing. Specify a conversation handle.

All Replies

  • Saturday, November 17, 2012 11:00 PM
     
      Has Code

    One method is to initialize @RecvReplyDlgHandle to NULL and check for NULL after the RECEIVE:

    DECLARE 
    	@RecvReplyMsg NVARCHAR(100) = NULL
    	@RecvReplyDlgHandle UNIQUEIDENTIFIER = NULL;
     
    BEGIN TRANSACTION;
     
    RECEIVE TOP(1)
    	@RecvReplyDlgHandle = conversation_handle
    	,@RecvReplyMsg = message_body
    FROM TargetQueue;
    
    IF @RecvReplyDlgHandle IS NOT NULL
    BEGIN
    	END CONVERSATION @RecvReplyDlgHandle;
    END;
     
    SELECT @RecvReplyMsg AS ReceivedReplyMsg;
     
    COMMIT TRANSACTION;
    

    The application can check ReceivedReplyMsg for NULL to indicate no message was received.


    Dan Guzman, SQL Server MVP, http://weblogs.sqlteam.com/dang/

  • Sunday, November 18, 2012 9:02 AM
    Moderator
     
     Answered

    Hi Licken,

    Please wrap your END CONVERSATION and SELECT ... in a:

    Code Block
    if(@@rowcount <> 0)
    begin
      end conversation ...
      select  @RcvReplyMsg
    end


    Iric Wen

    TechNet Community Support

    • Proposed As Answer by rrozema Monday, November 19, 2012 7:44 AM
    • Marked As Answer by licken borrows Saturday, November 24, 2012 1:46 PM
    •