SELECT
  CN.CMSCreditNoteID,
  CN.AccountBookType,
  CN.AccountBookID,
  SE.SageEntityName AS AccountBookName,
  CN.CreditNoteDate,
  CASE CN.CreditNoteAccount
    WHEN '1099-CAC'   THEN '109901'  -- C/N ANNUAL SUBSCRIPTION: CANCELLATION
    WHEN '1099-CAD'   THEN '109902'  -- CREDIT NOTES - LATE CANCELLATIONS
    WHEN '1099-CAO'   THEN '109903'  -- C/N ANNUAL SUBSCRIPTION: CHANGED TO MONTHLY
    WHEN '1099-CBA'   THEN '109904'  -- CREDIT NOTES - BARTER AGREEMENTS
    WHEN '1099-CBI'   THEN '109905'  -- C/N ADHOC - WRONG BILLING RE-INVOICED
    WHEN '1099-CC'    THEN '109906'  -- ADHOC: CLIENT CANCELLED TRAINING
    WHEN '1099-CDA'   THEN '109907'  -- C/N DISCOUNT ALLOWED
    WHEN '1099-CRA'   THEN '109909'  -- CREDIT NOTES - CANCELLATIONS / REFUNDS
    WHEN '1099-CRI'   THEN '109910'  -- CREDIT NOTES - WRONG BILLING & RE-INVOICE
    WHEN '1099-CRM'   THEN '109911'  -- CREDIT NOTES - MANUAL DECREASE / INCREASE ADJUSTMENT
    WHEN '1099-CRS'   THEN '109912'  -- C/N ADHOC - WRONG BILLING AS SUBSCRIPTION SERVICE COVER
    WHEN '1099-CRT'   THEN '109913'  -- C/N ADHOC: WRONG BILLING WRONG ACCOUNT
    WHEN '1099-CWP'   THEN '109914'  -- C/N ADHOC - WRONG BILLING WRONG PRICE
    WHEN '1099-PHD'   THEN '109915'  -- C/N SUBSCRIPTION: PAYMENT HOLIDAY BATCH 20
    WHEN '1099-RSF'   THEN '109916'  -- C/N SUBSCRIPTION SERVICE FAILURE
    WHEN '1096-ED'    THEN '109601'  -- CREDIT NOTES ED SUBSCRIPTION
    WHEN '1097-SED'   THEN '109701'  -- CREDIT NOTES SED SUBSCRIPTION
    WHEN '4001-AD'    THEN '400101'  -- C/N BAD DEBT ACTUAL WRITE-OFFS: HANDED OVER
    WHEN '4001-ADNHO' THEN '400102'  -- C/N BAD DEBT ACTUAL WRITE OFFS: NOT HANDED OVER
    ELSE CN.CreditNoteAccount
  END AS CreditNoteAccount,
  CASE CN.TaxType
    WHEN 'ZERORATED'    THEN '3'  -- Zero Rate
    WHEN 'EXEMPTOUTPUT' THEN '5'  -- Exempt
    WHEN 'BADDEBT'      THEN '8'  -- Bad Debts
    ELSE '1'                      -- Standard Rate Output
  END AS SageTaxType,
  CN.InvoiceNumber,
  CN.CreditNoteNumber,
  CN.ExternalInvoiceID,
  CN.ExternalCreditNoteID,
  CN.ActionDateTime,
  CN.Approver,
  CN.Updated,
  CN.Allocated,
  CN.CreditNoteAmount
FROM
  taCreditNote AS CN
    LEFT JOIN taSageEntity AS SE ON ((SE.SageEntityID = CN.AccountBookID) AND (CN.AccountBookType = 'Sage'))
WHERE
  (CN.AccountBookType = 'Sage') AND
  (CN.Updated = 0) AND
  ((CN.CreditNoteNumber IS NULL) OR (CN.CreditNoteNumber <> 'VOID'))
  @pAccountBookID
  @pFilter

-- For testing.
LIMIT 10