SELECT
  BM.AccountBookType,
  BM.AccountBookID,
  COALESCE(IF(BM.AccountBookType = 'Xero', XE.XeroEntityName, IF(BM.AccountBookType = 'Sage', SE.SageEntityName, NULL)), CONCAT(BM.AccountBookType, '_', BM.AccountBookID)) AS AccountBookName
FROM
  taAccountBookMember AS BM
    INNER JOIN taClients AS CS ON (CS.ClientID = BM.ClientID)
    LEFT JOIN taXeroEntity AS XE ON ((XE.XeroEntityID = BM.AccountBookID) AND (BM.AccountBookType = 'Xero'))
    LEFT JOIN taSageEntity AS SE ON ((SE.SageEntityID = BM.AccountBookID) AND (BM.AccountBookType = 'Sage'))
WHERE
  ((XE.Enabled = 1) OR (SE.Enabled = 1))
  @pBMClientID
  @pAccountBookID

UNION

SELECT
  CP.AccountBookType,
  CP.AccountBookID,
  COALESCE(IF(CP.AccountBookType = 'Xero', XE.XeroEntityName, IF(CP.AccountBookType = 'Sage', SE.SageEntityName, NULL)), CONCAT(CP.AccountBookType, '_', CP.AccountBookID)) AS AccountBookName
FROM
  taClientProducts AS CP
    INNER JOIN taClients AS CS ON (CS.ClientID = CP.ClientID)
    LEFT JOIN taXeroEntity AS XE ON ((XE.XeroEntityID = CP.AccountBookID) AND (CP.AccountBookType = 'Xero'))
    LEFT JOIN taSageEntity AS SE ON ((SE.SageEntityID = CP.AccountBookID) AND (CP.AccountBookType = 'Sage'))
WHERE
  ((XE.Enabled = 1) OR (SE.Enabled = 1)) AND
  (CP.Status = 1)
  @pCPClientID
  @pAccountBookID

ORDER BY
  AccountBookType,
  AccountBookID