CREATE PROCEDURE [dbo].[Sp_Queue]
    @NumberQueue SMALLINT OUTPUT,
    @FlagQueue CHAR(1),
    @UserId SMALLINT,
    @Status CHAR(1),
    @StartQueue SMALLINT = NULL,
    @LineNo TINYINT = 0
AS
BEGIN
    DECLARE @Queue AS TABLE
    (
        Row INT,
        Queue INT
    );

    INSERT INTO @Queue
    (
        Row,
        Queue
    )
    SELECT ROW_NUMBER() OVER (ORDER BY Queue) + (CASE
                                                     WHEN @FlagQueue = 0 THEN
                                                         @StartQueue - 1
                                                     ELSE
                                                         0
                                                 END
                                                ) Row,
           Queue
    FROM
    (
        SELECT Queue
        FROM dbo.TblQueue WITH (NOLOCK)
        WHERE DATEDIFF(DAY, DateDay, GETDATE()) = 0
        UNION
        SELECT NumberQueue Queue
        FROM dbo.TmpDrugH WITH (NOLOCK)
        WHERE Kind_Flag = 1
              AND NumberQueue IS NOT NULL
        UNION
        SELECT NumberQueue Queue
        FROM dbo.DrugH WITH (NOLOCK)
        WHERE Kind_Flag = 1
              AND DATEDIFF(DAY, Tarikh, GETDATE()) = 0
              AND NumberQueue IS NOT NULL
    ) AS T
    ORDER BY Queue;

    SELECT TOP 1
           @NumberQueue = Row
    FROM @Queue
    WHERE Row NOT IN
          (
              SELECT Queue FROM @Queue
          );

    IF ISNULL(@NumberQueue, 0) = 0
        SET @NumberQueue =
    (
        SELECT ISNULL(MAX(Queue), 0) + 1 FROM @Queue
    )   ;

    INSERT INTO dbo.TblQueue
    (
        Queue,
        StartTime,
        FlagQueue,
        User_id,
        QStatus,
        QSound,
        [LineNo]
    )
    VALUES
    (@NumberQueue, CONVERT(VARCHAR(5), GETDATE(), 108), @FlagQueue, @UserId, @Status, @Status, @LineNo);

    RETURN @NumberQueue;
END;