CREATE PROCEDURE [dbo].[GetTransactionsSaldo] @AAccountNumber INT, @AHotelCustomerNumber INT, @ASaldo MONEY OUTPUT, @ADateStamp CHAR(8) = '99991231' AS
SET NOCOUNT ON

/*
  Changes:
    KJ 20151221: Bug: Wrong amount if AHotelCustomerNumber = -1
    KJ 20151005: Added support for AHotelCustomerNumber = -1
*/

SET @ADateStamp = ISNULL(@ADateStamp, '99991231')

SELECT @ASaldo = SUM(Transactions.PriceOverwrite * (CASE Transactions.Debit WHEN 1 THEN 1 ELSE -1 END)*
CASE WHEN Accounts.AccountType IN (4,5,6) THEN 1 ELSE 1+(VatValue/100) END)
FROM Accounts WITH (NOLOCK)
FULL OUTER JOIN Transactions WITH (NOLOCK) ON Accounts.AccountNumber = Transactions.AccountNumber
WHERE 1=1
AND Accounts.AccountNumber = @AAccountNumber
AND (@AHotelCustomerNumber = -1 OR Transactions.HotelCustomerNumber = @AHotelCustomerNumber)
AND Accounts.Balance IN (1,2)
AND Transactions.DateStamp <= @ADateStamp
AND NOT Accounts.AccountType IN (1,2)
