CREATE FUNCTION [dbo].[GetTransactionResultAccount] (@AGlobalTransactionNumber int, @AWareNumber int, @AFolioNumber int)  
--nb20160616 Created Returns the AccountPk of the Result transaction leg.
RETURNS int AS  
BEGIN 
  DECLARE @ResultAccountPk int
  
  SELECT TOP 1 @ResultAccountPk=(CASE WHEN NOT ATR.AccountNumber IS NULL THEN TRA.AccountNumber ELSE ATR.AccountNumber END)
  FROM Transactions TRA WITH (NOLOCK)
    LEFT JOIN Accounts ATR WITH (NOLOCK) ON ATR.AccountNumber = TRA.AccountNumber AND ATR.Balance = 1
  WHERE TRA.GlobalTransactionNumber = @AGlobalTransactionNumber AND TRA.WareNumber = @AWareNumber AND TRA.FolioNumber = @AFolioNumber
  ORDER BY ATR.AccountNumber DESC, TRA.TransactionNumber

  RETURN @ResultAccountPk
END
