SELECT
  IH.CMSInvNo,
  IH.AppointmentID AS YearMonth,
  IH.DocumentNumber,
  IH.DocumentDate,
  IH.DueDate,
  IH.AccountCode,
  IH.Description,
  IH.Contact,
  IH.AccountBookType,
  COALESCE(IF(IH.AccountBookType = 'Pastel', PB.DatabaseName, IF(IH.AccountBookType = 'Xero', XE.XeroEntityName, IF(IH.AccountBookType = 'Sage', SE.SageEntityName, NULL))), CONCAT(IH.AccountBookType, '_', IH.AccountBookID)) AS AccountBookName,
  IH.InvoiceAmountIncl
FROM
  taInvoiceHeader AS IH
    LEFT JOIN taPastelBook AS PB ON ((PB.PastelBookID = IH.AccountBookID) AND (IH.AccountBookType = 'Pastel'))
    LEFT JOIN taSageEntity AS SE ON ((SE.SageEntityID = IH.AccountBookID) AND (IH.AccountBookType = 'Sage'))
    LEFT JOIN taXeroEntity AS XE ON ((XE.XeroEntityID = IH.AccountBookID) AND (IH.AccountBookType = 'Xero'))
WHERE
  (IH.InvoiceType = 'R') AND
  (IH.AppointmentID = @nYearMonth) AND
  (IH.AccountBookType = @aAccountBookType) AND
  (IH.AccountBookID = @nAccountBookID) AND
  (IH.Batch = CONCAT('Batch ', @nBatch)) AND
  (IH.Updated = 1) AND
  (IH.DocumentNumber <> 'VOID')
  @pInvoices

LIMIT 10;