-- Missing followup.
DECLARE @ReferenceNumber INT
DECLARE @HotelNumber INT
DECLARE @Iden INT
DECLARE @GuestNumber INT

DECLARE db_curRes CURSOR FOR
  SELECT Reservations.ReferenceNumber, HotelNumber, GuestNumber
  FROM Reservations WITH (NOLOCK)
  INNER JOIN ReservationMain WITH (NOLOCK) ON ReservationMain.ReferenceNumber = Reservations.ReferenceNumber
  WHERE Reservations.ReferenceNumber NOT IN (
    SELECT ReferenceNumber 
    FROM ReservationFollowupXtab rfx WITH (NOLOCK) 
    INNER JOIN Followup f WITH (NOLOCK) ON rfx.FollowupNumber = f.FollowupNumber AND SubType = 1
  )
  AND Reservations.ReferenceNumber > 0
OPEN db_curRes

FETCH NEXT FROM db_curRes INTO @ReferenceNumber, @HotelNumber, @GuestNumber

WHILE @@FETCH_STATUS = 0
BEGIN
  EXEC sp_executesql N'/*TFollowUPFX.ExecSQLBuild.SQLInsertBuild*/ INSERT INTO dbo.FollowUp WITH (ROWLOCK) (ReservationLog,HotelNumber,OverWritten,SubType,UserCreated,CreatedBy,CreatedDate,Note,State,Priority,Type,Date) VALUES ( @P1 , @P2 , @P3 , @P4 , @P5 , @P6 , @P7 , @P8 , @P9 , @P10 , @P11 , @P12 )', N'@P1 varchar(296),@P2 int,@P3 bit,@P4 int,@P5 bit,@P6 int,@P7 datetime,@P8 varchar(21),@P9 int,@P10 int,@P11 int,@P12 datetime', '', @HotelNumber, 0, 1, 0, 1, 'Jan 09 2008  2:17:15:527PM', 'Created with customer', 3, 17, 5, 'Jan 09 2008  2:17:15:527PM'
  SELECT @Iden = @@Identity
  EXEC sp_executesql N'/*TReservationFollowUpXTabFX.ExecSQLBuild.SQLInsertBuild*/ INSERT INTO dbo.ReservationFollowUpXTab WITH (ROWLOCK) (FollowUpNumber,GuestNumber,ReferenceNumber) VALUES ( @P1 , @P2 , @P3 )', N'@P1 int,@P2 int,@P3 int', @Iden, @GuestNumber, @ReferenceNumber

  FETCH NEXT FROM db_curRes INTO @ReferenceNumber, @HotelNumber, @GuestNumber
END

CLOSE db_curRes
DEALLoCATE db_curRes

-- Fix for Wrong subtype on followup for guest > 0
update followup set subtype = 1 where followupnumber in (
select followup.followupnumber
from followup WITH (nolock)
inner join reservationfollowupxtab WITH (nolock) on reservationfollowupxtab.followupnumber = followup.followupnumber
--  and reservationfollowupxtab.referencenumber = 28413
  and reservationfollowupxtab.guestnumber > 0
  and subtype <> 1 
  and note like 'created'
)