SELECT
  IA.EntryDate,
  IA.AccountBookType,
  COALESCE(IF(IA.AccountBookType = 'Pastel', PB.DatabaseName, IF(IA.AccountBookType = 'Xero', XE.XeroEntityName, IF(IA.AccountBookType = 'Sage', SE.SageEntityName, NULL))), CONCAT(AI.AccountBookType, '_', AI.AccountBookID)) AS AccountBookName,
  IA.RunNumber,
  IA.BatchNumber,
  IA.ClientID,
  IA.AccountCode,
  IA.CMSInvNo,
  BE.GroupName AS TradingName,
  IA.AppointmentID,
  IA.InvoiceNumber,
  IA.InvoiceAmountIncl,
  IA.ErrorDescription
FROM
  taInvoiceAudit AS IA
    LEFT JOIN taClients AS BE ON (BE.ClientID = IA.ClientID)
    LEFT JOIN taPastelBook AS PB ON ((PB.PastelBookID = IA.AccountBookID) AND (IA.AccountBookType = 'Pastel'))
    LEFT JOIN taXeroEntity AS XE ON ((XE.XeroEntityID = IA.AccountBookID) AND (IA.AccountBookType = 'Xero'))
    LEFT JOIN taSageEntity AS SE ON ((SE.SageEntityID = IA.AccountBookID) AND (IA.AccountBookType = 'Sage'))
WHERE
  (IA.InvoiceType IN (@pInvoiceType))
  @pRunNumber
  @pFromTo
  @pFilter
  @pBatch