CREATE FUNCTION dbo.OverNightDaysForOwnerReport (@AReferenceNumber INT, @AGuestNumber INT) RETURNS INT AS
/*
  Created By Kent Johansen, December 2024
  Get the number of nights for the reservation   
*/
BEGIN
  DECLARE @LReturn INT

  IF @AReferenceNumber > 0
  BEGIN
    IF @AGuestNumber = 0
    BEGIN
      SELECT @LReturn = CONVERT(INT, CONVERT(DATETIME, ReservationRoomLine.DepartureDate, 112) - CONVERT(DATETIME, ReservationRoomLine.ArrivalDate, 112))
      FROM ReservationRoomLine WITH (NOLOCK)
      INNER JOIN ReservationRoomLineXtab WITH (NOLOCK) ON ReservationRoomLineXtab.LineNumber = ReservationRoomLine.LineNumber
        AND ReservationRoomLineXtab.ReferenceNumber = @AReferenceNumber
        AND ReservationRoomLineXtab.GuestNumber = 0
    END
    ELSE
    BEGIN
      SELECT @LReturn = CONVERT(INT, CONVERT(DATETIME, Reservations.DepartureDate, 112) - CONVERT(DATETIME, Reservations.ArrivalDate, 112))
      FROM Reservations WITH (NOLOCK)
      WHERE ReferenceNumber = @AReferenceNumber
      AND GuestNumber = @AGuestNumber
    END
  END
  ELSE
    SET @LReturn = 0
  
  RETURN @LReturn
END