CREATE FUNCTION [dbo].[GetTaxAmount] (@TransactionNumber int)
RETURNS Money AS
BEGIN
--nb20140703 Created
--Determine the retrival method (product, ware...)
  DECLARE @Tax MONEY
  --ware
  SELECT @Tax = (SELECT SUM(T1.PriceOverwrite * (CASE T1.Debit WHEN 1 THEN -1 ELSE 1 END))
    FROM dbo.Transactions T1 WITH (NOLOCK)
      INNER JOIN dbo.Accounts A WITH (NOLOCK) ON A.AccountNumber = T1.AccountNumber AND A.Balance = 2 AND A.VAT > 1
    WHERE T1.FolioNumber = TR.FolioNumber AND T1.GlobalTransactionNumber = TR.GlobalTransactionNumber
    )
  FROM dbo.Transactions TR WITH (NOLOCK)
  WHERE TR.TransactionNumber=@TransactionNumber AND (TR.Payment = 0 AND ISNULL(TR.ProductWareLinkNumber, 0)<=0)
  IF @Tax IS NULL  
    --product
    SELECT @Tax = (SELECT SUM(T1.PriceOverwrite * (CASE T1.Debit WHEN 1 THEN -1 ELSE 1 END))
      FROM dbo.Transactions T1 WITH (NOLOCK)
         INNER JOIN dbo.Accounts A WITH (NOLOCK) ON A.AccountNumber = T1.AccountNumber AND A.Balance = 2 AND A.VAT > 1
      WHERE T1.FolioNumber = TR.FolioNumber AND T1.ProductWareLinkNumber= TR.ProductWareLinkNumber
      )
    FROM dbo.Transactions TR WITH (NOLOCK)
    WHERE TR.TransactionNumber=@TransactionNumber AND ISNULL(TR.ProductWareLinkNumber, 0)>0
  
--Get and Return the tax amount  
  RETURN @Tax
END


