SET NOCOUNT ON
Declare @Domino Int
select @Domino = ISNULL(KeyValue, 0) from HotelSetup WITH (nolock) where searchkey like '%CentralBookingType%'
if @Domino > 0 
begin
declare @FolioNumber int 
, @ReferenceNumber int
, @ResHCN int
, @FolioHCN int
, @LogTextFolio VARCHAR(50)

PRINT ' Fix hotel relations on all reservation folios'
PRINT '-------------------------------------------------'
declare #BillCur cursor FAST_FORWARD READ_ONLY for
select distinct F.FolioNumber
, F.ReferenceNumber
, C.CustomerNumber
, F.HotelCustomerNumber
from folios F WITH (nolock) 
  inner join reservationmain rm WITH (nolock) on f.referencenumber = rm.referencenumber
  left join customer C WITH (nolock) on rm.HotelNumber = c.HotelNumber
where ISNULL(C.CustomerNumber, 0) > 0 AND (F.HotelCustomerNumber <> C.CustomerNumber) 
open #BillCur
fetch Next from #BillCur
into @FolioNumber, @ReferenceNumber, @ResHCN, @FolioHCN
while @@FETCH_STATUS = 0 -- safe
begin
  SET @LogTextFolio = ''
  if ISNULL(@ResHCN, -1) <> -1 and @FolioHCN <> @ResHCN
  begin 
    update folios set HotelCustomerNumber = @ResHCN where folionumber = @FolioNumber
    SET @LogTextFolio = ' Changed Folio= ' + Convert(varchar, @FolioNumber) + ' OldHotelValue= '+ Convert(varchar, @FolioHCN)
    SET @FolioHCN = @ResHCN 
    PRINT 'Reference= ' + CONVERT(VARCHAR, @ReferenceNumber) + ' on Hotel= ' + CONVERT(VARCHAR, @ResHCN) + @LogTextFolio
  end
  fetch Next from #BillCur
  into @FolioNumber, @ReferenceNumber, @ResHCN, @FolioHCN
end
close #BillCur
deallocate #BillCur
end
