SELECT

  -- Invoice detail.
  IH.CMSInvNo,
  IH.DocumentNumber AS InvNumber,
  IH.DocumentDate,
  IH.AccountBookType,
  IH.AccountBookID,
  IH.DocumentNumber,
  IH.AccountCode,
  IH.Description,
  IH.Updated,
  IH.Batch,
  IH.AppointmentID,
  IH.InvoiceType,
  IH.DueDate,
  IH.PaymentDate,
  IH.AmountPaid,
  IH.ExternalID,

  -- Client detail
  IH.ClientID AS CMSClientID,
  IH.TradingName,
  IH.TaxTypeID,
  ROUND(IH.TaxRate, 4) AS TaxRate,
  IH.PaymentMethod,
  IH.VATNumber,
  IH.OrderNumber,
  IH.Address1,
  IH.Address2,
  IH.Address3,
  IH.Address4,
  IH.Address5,
  IH.Consultant,
  IH.Contact,
  IH.Postal1,
  IH.Postal2,
  IH.Postal3,
  IH.PostalCode,
  IH.Telephone,
  IH.Fax,

  -- Account Book - Sage
  CASE IH.TaxTypeID
    WHEN  6 THEN '3'
    WHEN  7 THEN '5'
    WHEN 17 THEN '8'
    ELSE '1'
  END AS SageTaxAccount,
  SE.SageEntityName,

  -- Account Book - Combined.
  SE.SageEntityName AS AccountBookName,
  SE.InvoicePrefix AS InvoicePrefix,

  -- Ad Hoc Only
  BE.ImmediateAdhocInvoices,
  BE.IndividualAdhocInvoices,

  -- Amounts
  IH.InvoiceAmountIncl AS InvTotIncl,
  IH.InvoiceAmountExcl AS InvTotExcl,
  IH.InvoiceAmountExcl * IH.TaxRate AS InvTotTax,

  '' AS ErrorDescription
FROM
  taInvoiceHeader AS IH
    INNER JOIN taClients AS BE ON (BE.ClientID = IH.ClientID)
    INNER JOIN taSageEntity AS SE ON ((SE.SageEntityID = IH.AccountBookID) AND (IH.AccountBookType = 'Sage'))
WHERE
  (IH.InvoiceType IN ('A','I','R')) AND
  (IH.AccountCode <> 'NONE') AND
  (IH.Updated = 0) AND
  (IH.DocumentNumber <> 'VOID')
  @pFilter
ORDER BY
  IH.AccountBookID,
  IH.CMSInvNo
