SELECT
  IH.CMSInvNo,
  IH.AppointmentID,
  IH.DocumentNumber,
  IH.DocumentDate,
  IH.Updated,
  IH.AccountCode,
  IH.ClientID,
  IH.Consultant,
  IH.Telephone,
  IH.Fax,
  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,
  BE.IndividualAdhocInvoices,
  IF(IH.Updated = 0, '<img src="/main/image/RedCross.png">', '') AS DelIcon
FROM
  taInvoiceHeader AS IH
    LEFT JOIN taClients AS BE ON (BE.ClientID = IH.ClientID)
    LEFT JOIN taPastelBook AS PB ON ((PB.PastelBookID = IH.AccountBookID) AND (IH.AccountBookType = 'Pastel'))
    LEFT JOIN taXeroEntity AS XE ON ((XE.XeroEntityID = IH.AccountBookID) AND (IH.AccountBookType = 'Xero'))
    LEFT JOIN taSageEntity AS SE ON ((SE.SageEntityID = IH.AccountBookID) AND (IH.AccountBookType = 'Sage'))
    LEFT JOIN tbAppointments AS AP ON (AP.AppointmentID = IH.AppointmentID)
WHERE
  1
  @pClientID
  @pShowVoid
  @pShowUpdated
  @pFilter