
CREATE PROCEDURE DBO.[GetDepositumDiff] (@ref int, @guestnumber int) AS
SET NOCOUNT ON

  declare @price money
  declare @debit int
  declare @recieved money   set @recieved = 0.00
  declare @wanted money     set @wanted   = 0.00
  declare @diff money       set @diff     = 0.00

  declare dep_cur cursor for
    SELECT debit, (Transactions.Pieces * Transactions.PriceOverWrite) as price
    FROM 
      FollowUp WITH (nolock) INNER JOIN
      Transactions WITH (nolock) ON FollowUp.FollowUpNumber = Transactions.DepositfollowupNumber INNER JOIN
      ReservationFollowUpXTab WITH (nolock) ON FollowUp.FollowUpNumber = ReservationFollowUpXTab.FollowUpNumber
    WHERE ReservationFollowUpXTab.referencenumber = @ref and ReservationFollowUpXTab.guestnumber = @guestnumber and showonbillflag = 1
  open dep_cur
  fetch next from dep_cur into @debit, @price
  while @@fetch_status = 0
  begin
    if @debit = 1 set @recieved = @recieved + @price
    fetch next from dep_cur into @debit, @price
  end
  close dep_cur
  deallocate dep_cur

  declare fol_cur cursor for
    select depositamount from 
      reservationfollowupxtab WITH (nolock) inner join 
      followup WITH (nolock) on followup.followupnumber = reservationfollowupxtab.followupnumber 
    where referencenumber = @ref and guestnumber = @guestnumber and type = 15
  open fol_cur
  fetch next from fol_cur into @price
  while @@fetch_status = 0
  begin  
    set @wanted = @wanted + @price
    fetch next from fol_cur into @price
  end
  close fol_cur
  deallocate fol_cur

  set @diff = @wanted - @recieved
  select @diff as Diff

