CREATE PROCEDURE DBO.CopyReservationGroup @OldReferenceNumber INT, @FirstAddressNumber INT, @FirstRoomLineNumber INT, @NewReferenceNumber INT OUTPUT, @UserIDNumber INT, @NewReferenceNumberOverwrite INT=0  AS
SET NOCOUNT ON
/*
    DEPENDENCIES: CopyReservation

    Created by Jacob Pedersen 09-08-2002

    Last updated: Jacob Pedersen 20-03-2003 @FirstAddressNumber OUTPUT, @FirstRoomLineNumber OUTPUT

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

*/

DECLARE
@OldGuestNumber INT,
@NewGuestNumber INT

SET @NewReferenceNumber = 0

DECLARE #CopyCurGroup CURSOR FORWARD_ONLY FOR

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

OPEN #CopyCurGroup

FETCH NEXT FROM #CopyCurGroup
INTO @OldGuestNumber

WHILE (@@FETCH_STATUS <> -1)
BEGIN
  EXEC CopyReservation @OldReferenceNumber, @OldGuestNumber, @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 @OldGuestNumber
END

CLOSE #CopyCurGroup
DEALLOCATE #CopyCurGroup

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 TransferArrangementToNewRef @OldReferencenumber,@OldGuestNumber,@NewReferencenumber,@NewGuestNumber --av 230902

