Search code examples
sql-serverservice-broker

do we have to write while (1=1) in activation stored procedures for service broker queues always or it's an optional?


e.g.:

Create Proc test_act_sp  
AS  
    BEGIN  
        WHILE (1=1)  
            BEGIN  
                WAITFOR  
                (  
                    RECIEVE TOP(1) FROM Queue  
                )  
            ........
            ........
            ........
        END
    END

Solution

  • Generally the code looks like this

    Create Proc test_act_sp  
    AS  
    BEGIN  
        WHILE (1=1)  
            BEGIN  
                WAITFOR  
                (  
                    RECIEVE TOP(1) ... FROM Queue  
                ) , TIMEOUT 3000; --Timeout value can be changed.
    
                IF (@@ROWCOUNT = 0)
                BEGIN
                   BREAK; 
                END
            ........
            ........
            ........
        END
    END
    

    The activation procedure starts message processing within infinite loop, and if it doesn't recieve any messages within timout interval (3sec in the above example), the procedure will be terminated.

    If we have a bulk of messages sent to queue, the activation procedure will be started and loaded into memory once for all the set (as it waits for the messages after activation), and will be shut down 3 seconds after the last recieved message. So the while loop in this case reduce overhead for the server.

    It's possible to omit loop, but in this case the activation procedure will be triggered for each message in queue, which might cause performance issues.