Friday, October 14, 2011

CAML query on number field with BeginsWith--Work around

I faced problem when I tried to filter my list with BeginsWith operator on number column. It may treat the condition as "Eq" because of the Data type Number.

The work around I found is , create another column as Calculated. The twist here is , again it considers the condition as "Eq". So the formula i used is "=CONCATENATE("A",Column1)". Select the data type of Calculated field as Single Line Of Text.

Now my condition to filter is  <BeginsWith> <Value>A + our Field Value</value>

My Code is here:-

Create Calculate Field
strDispName = lstFAS.Fields.Add(strDeptColName + "Dup", SPFieldType.Calculated, false);
                fldCalc = (SPFieldCalculated)lstFAS.Fields[strDeptColName + "Dup"];
                fldCalc.Formula = @"=CONCATENATE(""A"",[Department])";
                fldCalc.Update();


Query
SPQuery queryFAS_ByCondition = new SPQuery();
                        queryFAS_ByCondition.Query = string.Format("<Where><BeginsWith><FieldRef Name='DepartmentDup' /><Value Type='Text'>{0}</Value></BeginsWith></Where>",
                                                               "A"+lstItemFASSiteFinder_ByID.Title);


The code may look ugly, but hey it worked for me.

happy coding....:-)