SELECT
  CN.CMSCreditNoteID,
  CN.AccountBookType,
  CN.AccountBookID,
  COALESCE(IF(CN.AccountBookType = 'Pastel', PB.DatabaseName, IF(CN.AccountBookType = 'Xero', XE.XeroEntityName, IF(CN.AccountBookType = 'Sage', SE.SageEntityName, NULL))), CONCAT(CN.AccountBookType, '_', CN.AccountBookID)) AS AccountBookName,
  CN.CreditNoteDate,
  CN.CreditNoteAccount,
  CN.TaxType AS XeroTaxAccount,
  CN.InvoiceNumber,
  CN.CreditNoteNumber,
  CN.ExternalCreditNoteID,
  CN.ActionDateTime,
  CN.Approver,
  CN.Updated,
  CN.Allocated,
  CN.CreditNoteAmount
FROM
  taCreditNote AS CN
    LEFT JOIN taPastelBook AS PB ON ((PB.PastelBookID = CN.AccountBookID) AND (CN.AccountBookType = 'Pastel'))
    LEFT JOIN taXeroEntity AS XE ON ((XE.XeroEntityID = CN.AccountBookID) AND (CN.AccountBookType = 'Xero'))
    LEFT JOIN taSageEntity AS SE ON ((SE.SageEntityID = CN.AccountBookID) AND (CN.AccountBookType = 'Sage'))
WHERE
  CN.CMSCreditNoteID = @nCMSCreditNoteID