CREATE PROCEDURE [dbo].[Sp_Queue]  @NumberQueue Smallint Output , @FlagQueue Char(1), @UserId smallint
AS
Declare @MaxQ Smallint
Declare @MaxO Smallint

IF @FlagQueue = '0 '
Begin
  IF Exists(Select Queue From TblQueue Where Queue = 200 And DateDay = Convert(Varchar(10), GetDate(), 111))
  Begin
      Select @MaxQ = IsNull(Max(Queue),0) From TblQueue Where DateDay = Convert(Varchar(10), GetDate(), 111)
      And FlagQueue = '0'
      Select @MaxO = IsNull(Max(Queue),0) From TblQueue Where DateDay = Convert(Varchar(10), GetDate(), 111)
      And FlagQueue = '1'
      IF @MaxQ < @MaxO 
         Set @NumberQueue = @MaxO + 1
      Else
         Set @NumberQueue = @MaxQ + 1
  End
  Else
  Begin
      Insert Into TblQueue (Queue, StartTime, FlagQueue, User_id) 
      Values(200, Convert(Varchar(5), Getdate(),108),'0',@UserId )
      Set @NumberQueue = 200
      Return @NumberQueue
  End      
End
Else
Begin
   Select @MaxQ = IsNull(Max(Queue),0) From TblQueue Where DateDay = Convert(Varchar(10), GetDate(), 111)
   And FlagQueue = '0'
   Select @MaxO = IsNull(Max(Queue),0) From TblQueue Where DateDay = Convert(Varchar(10), GetDate(), 111)
   And FlagQueue = '1'
  IF Exists(Select Queue From TblQueue Where Queue =  @MaxO + 1  And DateDay = Convert(Varchar(10), GetDate(), 111))
      Set @NumberQueue = @MaxQ + 1
   Else
      Set @NumberQueue = @MaxO + 1
End

 ------------------------------------------------------------------------------------------------------------------------------
  ---Search TmpDrugH And DrugH
 Declare Cursor_Search  Cursor For 
 Select @NumberQueue 
 Open Cursor_Search 
 Fetch Next FRom Cursor_Search Into @NumberQueue 
 While @@Fetch_Status = 0 
 Begin   
   While @NumberQueue > 0   
   Begin     
     IF Exists(Select NumberQueue From TmpDrugH Where NumberQueue = @NumberQueue 
      And Convert(Varchar(10), Tarikh,111)  =  Convert(Varchar(10), GetDate(),111))       
       Set @NumberQueue = @NumberQueue + 1   
    Else   
     Begin     
       IF Exists(Select NumberQueue From DrugH Where NumberQueue = @NumberQueue 
       And  Convert(Varchar(10), Tarikh,111)  =  Convert(Varchar(10), GetDate(),111))       
         Set @NumberQueue = @NumberQueue + 1     
       Else       
         Break   
     End 
   End 
   While @NumberQueue > 0 
   Begin   
     IF Exists(Select NumberQueue From DrugH Where NumberQueue = @NumberQueue 
     And  Convert(Varchar(10), Tarikh,111)  =  Convert(Varchar(10), GetDate(),111))     
       Set @NumberQueue = @NumberQueue + 1   
     Else     
       Break 
   End 
   Fetch Next From Cursor_Search Into @NumberQueue 
 End 
 Close Cursor_Search 
 Deallocate Cursor_Search 
 ------------------------------------------------------------------------------------------------------------------------------
 Insert Into TblQueue (Queue, StartTime, FlagQueue, User_id) 
 Values(@NumberQueue, Convert(Varchar(5), Getdate(),108),@FlagQueue, @UserId)

Return @NumberQueue
