CREATE FUNCTION [dbo].[GetBalanceReceipt] (@FolioNumber INT, @PkInvoice INT) 
RETURNS @BalanceReceipt TABLE (Price MONEY, Tax MONEY, FkInvoice INT) AS
BEGIN
/*
nbl20161229: Created
Notes: Calculates the Invoice balance and return price and Tax amounts 
Changes:
*/
DECLARE @Amount MONEY, @IsTax BIT, @Price MONEY, @Tax MONEY
SET @Price = 0
SET @Tax = 0
DECLARE Cur CURSOR FAST_FORWARD READ_ONLY FOR
SELECT Amount, Tax FROM [dbo].[GetTaxSpecReceipt] (@FolioNumber, @PkInvoice)
OPEN Cur
FETCH NEXT FROM Cur INTO @Amount, @IsTax
WHILE @@FETCH_STATUS <> -1
BEGIN
  IF @IsTax = 0
    SET @Price = @Price + @Amount
  ELSE
    SET @Tax = @Tax + @Amount
  FETCH NEXT FROM Cur INTO @Amount, @IsTax
END
CLOSE Cur
DEALLOCATE Cur

INSERT INTO @BalanceReceipt (Price, Tax, FkInvoice) VALUES (@Price, @Tax, @PkInvoice)

  RETURN 
END 