CREATE PROCEDURE DBO.CopyReservationToDBGroup @DestDB VARCHAR(50), @ReferenceNumber INT, @FirstAddressNumber INT, @FirstRoomLineNumber INT, @NewReferenceNumber INT OUTPUT, @UserIDNumber INT, @NewReferenceNumberOverwrite INT=0  AS
SET NOCOUNT ON
/*
    DEPENDENCIES: CopyReservationToDB

    Created by Jacob Pedersen 2007209

    Last updated: 

    NOTE: - This routine makes a copy of a whole group and gives it a new referencenumber. It returns the new referencenumber

*/

DECLARE
@GuestNumber INT,
@NewGuestNumber INT

SET @NewReferenceNumber = 0

DECLARE #CopyCurGroup CURSOR FORWARD_ONLY FOR

  SELECT GuestNumber FROM dbo.Reservations WITH (NOLOCK) WHERE ReferenceNumber=@ReferenceNumber
  ORDER BY GuestNumber -- 0 must be first!!

OPEN #CopyCurGroup

FETCH NEXT FROM #CopyCurGroup
INTO @GuestNumber

WHILE (@@FETCH_STATUS <> -1)
BEGIN
  EXEC dbo.CopyReservationToDB @DestDB, @ReferenceNumber, @GuestNumber, @NewReferenceNumber OUTPUT, @NewGuestNumber OUTPUT, @UserIDNumber, @FirstAddressNumber OUTPUT, @FirstRoomLineNumber OUTPUT, @NewReferenceNumberOverwrite

  IF @NewReferenceNumberOverwrite = 0
    SET @NewReferenceNumberOverwrite = @NewReferenceNumber  -- Only set it after first call!

  FETCH NEXT FROM #CopyCurGroup
  INTO @GuestNumber
END

CLOSE #CopyCurGroup
DEALLOCATE #CopyCurGroup

--???should be no need SET @NewReferenceNumber = @NewReferenceNumberOverwrite -- should be the same!

--IF (@OldReferenceNumber <> @NewReferenceNumber)  --av 230902 Only copy arrangement if we copy to a new ref no. if we only copy a subres then we should just call sp GenerateArrangementformnamelist (TODO: do that!!)
--  Exec dbo.TransferArrangementToNewRef @OldReferencenumber,@OldGuestNumber,@NewReferencenumber,@NewGuestNumber --av 230902

