CREATE PROCEDURE DBO.CopyArrangementDayNotes  @ReferenceNumber int,  @SourceDate datetime, @DestDate datetime  AS
SET NOCOUNT ON

-- 20121121 RN: Replaced IS NULL with ISNULL
--sidsts rettet 2007 0410

Declare @arrNumber int
Declare @Time Char (5)
Declare @Price real
Declare @TotalPrice real
Declare @Pieces int
Declare @WareText char (50)
--Declare @Departments VARCHAR(32)
Declare @PK_Department INT
Declare @FK_Exdepartment INT
Declare @PlaceText char (20)
Declare @WareNumber int
Declare @FoundArrNumber int
Declare @note varchar (4000)

--Declare @IdentityValue int

Declare @FormatedSourceDate Char (10)
Declare @FormatedDestDate Char (10)
Declare @Tolerance char(5)

select  @FormatedSourceDate =  Convert (Char (10), @SourceDate, 112)
select  @FormatedDestDate =  Convert (Char (10), @DestDate, 112)

-- FIND THE TOLERANCE IN HOTELSETUP
Select @Tolerance = Keyvalue from hotelsetup WITH (nolock) where SearchKey ='ArrTimeTolerance'

Declare CopyDay Cursor For
SELECT ArrangementLineNumber,Time, Price, TotalPrice, Pieces, WareText,  FK_ExDepartment, PlaceText,WareNumber,note 
FROM ArrangementLines WITH (nolock) 
where  ArrangementLines.ArrangementLineNumber in (select arrangementLineNumber from arrangementReservationsXtab WITH (nolock) where referencenumber=@referencenumber)
and  ArrangementLines.date = @FormatedSourceDate

  Open Copyday
  Fetch Next From Copyday
  Into @ArrNumber,@Time, @Price, @TotalPrice, @Pieces, @WareText,  @FK_ExDepartment,@PlaceText,@WareNumber,@note

  -- Loop through records of sourcedate
  While  (@@FETCH_STATUS = 0)
  Begin
      select @FoundArrNumber = ArrangementLinenumber from ArrangementLines WITH (nolock) where
                                         WareNumber = @WareNumber and
                                         Price = @Price and
                                        (ISNULL(FK_exdepartment,0)= 0) and
                                        (Time = @Time or ( abs(DATEDIFF(Minute,Convert (DateTime,@Time,108), Convert (DateTime,Time,108)) ) <=  abs (Datediff (Minute, @Tolerance,Convert(datetime,'00:00',108)  )    )  ))
                                        and  date = @FormatedDestDate
                                        and arrangementLines.ArrangementLineNumber in (select distinct
                                        ArrangementReservationsXTab.ArrangementLineNumber  from
                                        arrangementReservationsXtab WITH (nolock) where arrangementReservationsXtab.Referencenumber =@Referencenumber )

      if ISNULL(@foundArrNumber, 0) > 0
        update arrangementlines set note = cast(note as varchar(4000) ) +@note where arrangementlinenumber=@foundarrnumber

    Fetch Next From CopyDay Into @ArrNumber,@Time, @Price, @TotalPrice, @Pieces, @WareText, @FK_ExDepartment,@PlaceText,@WareNumber,@note
  end

  Close Copyday
  Deallocate CopyDay

