CREATE PROCEDURE [dbo].[CopyAllotments] 
  @BaseCustomer INTEGER,
  @TargetCustomer INTEGER,
  @HotelNumber INTEGER
AS

/*
Changes:
  VD 20150102: EXT: New procedure handling customer allotments being moved from CustomerFieldsPerHotel to CustomerAllotmentsXTab  
*/

  DECLARE @AllotmentNumber INTEGER

BEGIN
  DELETE FROM CustomerAllotmentsXTab
  WHERE CustomerNumber = @TargetCustomer AND HOTELNUMBER = @HotelNumber

  DECLARE AllotmentCursor CURSOR FOR
  SELECT AllotmentNumber
  FROM CustomerAllotmentsXTab WITH (NOLOCK)
  WHERE CustomerNumber = @BaseCustomer AND HOTELNUMBER = @HotelNumber 

  OPEN AllotmentCursor
  FETCH NEXT FROM AllotmentCursor
  INTO @AllotmentNumber

  WHILE @@Fetch_status = 0
  BEGIN
    IF NOT EXISTS (SELECT 1 FROM CUSTOMERFIELDSPERHOTEL WITH (NOLOCK) 
               WHERE CustomerNumber = @TargetCustomer AND HOTELNUMBER = @HotelNumber)
      INSERT INTO CustomerFieldsPerHotel (CustomerNumber, HotelNumber)
      VALUES (@TargetCustomer, @HotelNumber) 

    INSERT INTO CustomerAllotmentsXTab (CustomerNumber, HotelNumber, AllotmentNumber)
    VALUES (@TargetCustomer, @HotelNumber, @AllotmentNumber)
	
    FETCH NEXT FROM AllotmentCursor
    INTO @AllotmentNumber
  END

  CLOSE AllotmentCursor
  DEALLOCATE AllotmentCursor
END

