function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Jim CripeJim Cripe 

Querying AutoNumber Values in the Where Clause

I had a query against an "Auto Number" column in an object using an Integer variable in a test method.

The test started failing in Spring '09.  I figured out why and thought I would share what I found (I haven't found a good example for querying AutoNumbers with Integer variables so I thought I would share how to do that too.)

In Spring '09, the Apex test record generator apparently started creating large integers instead of the next values in the normal sequence for the Auto Number field, and that revealed a problem in the code.  My test method was working when the values SaleForce generated for AutoNumbers when in the 300s range, but when it started feeding 10000 and above, the test started failing.)

Here is some example code:

Integer myAutoNumber_ID = 12340; //The test case was generating a large auto number in a record. (This example isn't best practice, but an example only. You should always create a test record and query it back to get the AutoNumber value generated to query with.)

//Test 1: Assertion will fail
MyObject__c[] mo = [select ID from MyObject__c where myAutoNumber_ID = : myAutoNumber_ID.format() ];
System.assertequals(1, mo .size(), 'MyObject size via format failed! No record found!');

Test 2: Ok
MyObject__c[] mo = [select ID from MyObject__c where myAutoNumber_ID = : '' + myAutoNumber_ID ];
System.assertequals(1, mo .size(), 'MyObject size via concatentation failed! No record found!');

 

In the "Test 1" example above, the assertion fails because the Integer "format" function inserts commas in the string it generates, and the Auto Number field doesn't have commas in it.  Once Auto Number starts being generated with values large enough to have commas, no record will ever be found because number strings like '1234' don't match those with commas like '1,234'.

"Test 2" above goes through.  The values to search for have to use the same type as the field queried, ("MyObject__c[] mo = [select ID from MyObject__c where myAutoNumber_ID = : myAutoNumber_ID ]" won't even compile.)

Concatenating an empty String to the Integer forces Apex to convert the Integer to a String value, but doesn't insert any commas in the resultant String so the record is found and the assertion passes.

Message Edited by Jim Cripe on 01-28-2009 08:27 AM