Crash when Filtering on Missing Constituent Codes

I wrote some code for a client a while back and tested it thoroughly and everything worked fine. There was somewhat of a delay before the client was due to implement it and when they ran the application it crashed at the beginning. After some investigation we worked out what was going on. The code gathered together a collection of constituents that had two constituent codes. Only now one of them was no longer in The Raiser’s Edge.

The code was quite straight forward really:

Dim constits As CRecords = Nothing
Dim filter As CRecordsFilter
Dim constits2 As IBBRecords2 = Nothing
Dim constit As CRecord = Nothing
Try
   constits = New CRecords
   constits.Init(REUtil.getSessionContext, topViewFilter_Record.tvf_record_UseFilterObject)
   constits2 = constits
   filter = constits2.FilterObject
   filter.IncludeConstituentCodes.Add("General", "General")
   filter.IncludeConstituentCodes.Add("Donor", "Donor")
   For Each constit In constits
      'Processing continues here

The problem was though when I ran the code I got the following error:

System.Runtime.InteropServices.COMException (0x80042722): General ODBC Error:
 [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near ')'.
Native error:102
at Blackbaud.PIA.RE7.BBREAPI.CRecordsClass.Count()

I have cut the stack trace short. This made no sense until we traced the SQL that was going to the database and saw the following:

SELECT  COUNT(*)  FROM DBO.RECORDS WHERE  
( EXISTS (SELECT
CONSTITUENT_CODES.ID  FROM DBO.CONSTITUENT_CODES
WHERE (CONSTITUENT_CODES.CONSTIT_ID = RECORDS.ID)
AND (CONSTITUENT_CODES.CODE IN (4043, ))  ))  

As you can see there is a value missing. After the 4043 (which I assume was for the constituent code “General”) there is no value. Looking in the system it appears that the “Donor” constituent code has been removed.

I am amazed that such a scenario would cause the plugin to crash. You would have thought that RE would check the existance of the values it puts in rather than leaving a blank value.