CREATE FUNCTION [dbo].[GetArrangementLineTextArrDep](@ADate VARCHAR(8), @AReferenceNumber INT, @AGuestNumber INT, @AToDate CHAR(8) ='', @ADateFormat VARCHAR(50)) RETURNS VARCHAR (8000) AS
BEGIN  
  DECLARE @ArrTime VARCHAR(5)
  DECLARE @WareText VARCHAR(255)
  DECLARE @Date CHAR(8)
  DECLARE @dummy INT
  DECLARE @curDate VARCHAR(8)
  DECLARE @Result VARCHAR (8000)
  DECLARE @Arr24HoursStarts CHAR(5)
  SELECT @Arr24HoursStarts = KeyValue FROM HotelSetUp WITH (NOLOCK) WHERE SearchKey = 'Arr24HoursStarts'
  IF ISNULL(@Arr24HoursStarts, '') = ''
    SET @Arr24HoursStarts = '07:00'

  SET @Result = ''
  SET @curDate = ''

  DECLARE GetArrLineTextCur CURSOR FAST_FORWARD READ_ONLY FOR
    SELECT CASE WHEN (ISNULL(ArrangementLines.Time, '') = '') THEN '00:00' ELSE ArrangementLines.Time END, ArrangementLines.WareText, ArrangementLines.Date,
    CASE WHEN CASE WHEN (ISNULL(ArrangementLines.Time, '') = '') THEN '00:00' ELSE ArrangementLines.Time END < '05:00' THEN ArrangementLines.Date ELSE ArrangementLines.Date - 1 END AS CalcStartDate
    FROM ArrangementLines WITH (NOLOCK)
    INNER JOIN ArrangementReservationsXtab WITH (NOLOCK) ON ArrangementLines.ArrangementLineNumber = ArrangementReservationsXtab.ArrangementLineNumber
    WHERE ArrangementReservationsXtab.ReferenceNumber = @AReferenceNumber
      AND ArrangementReservationsXtab.GuestNumber = @AGuestNumber
    AND (
      (@AToDate = '' AND ArrangementLines.Date = @ADate) OR
      (@AToDate <> '' AND ArrangementLines.Date >= @ADate AND ArrangementLines.Date <= @AToDate)    
    )
    ORDER BY CalcStartDate, ArrangementLines.Time ASC
  OPEN GetArrLineTextCur

  FETCH NEXT FROM GetArrLineTextCur INTO @ArrTime, @WareText, @Date, @dummy

  WHILE (@@FETCH_STATUS <> -1)
  BEGIN
    IF @Result <> ''
      SET @Result = @Result + CHAR(13) + CHAR(10)
    IF @AToDate <> '' AND @Date <> @curDate
    BEGIN
      IF @Result <> ''
        SET @Result = @Result + CHAR(13) + CHAR(10)
      SET @Result = @Result + FORMAT(CONVERT(DATETIME, @Date, 112), @ADateFormat) + CHAR(13) + CHAR(10)
    END
      
    SET @Result = @Result + @ArrTime + ': ' + @WareText 

    SET @curDate = @Date
    FETCH NEXT FROM GetArrLineTextCur INTO @ArrTime, @WareText, @Date, @dummy
  END
  CLOSE GetArrLineTextCur
  DEALLOCATE GetArrLineTextCur
  RETURN @Result  
END