The first part of my tips series on SPQuery class covered the basics of building a CAML query string to filter data from a SPList programmatically. However, a lot more complex data retrieval operation can be achieved using the SPQuery. Over here we will try to build more complex CAML queries with multiple And/Or conditions within it.
For instance, lets us take the case of s State list which holds all the states of India grouped by different zones i.e. North, South, East and West. We now need to run a query to filter out the states belonging to North and South zone. We would ideally prefer to use an OR condition with the SPQuery to retrieve the required output.
SPQuery stateQuery = new SPQuery(); stateQuery.Query = "<Where> <Or> <Eq><FieldRef Name=\"Zone\"/><Value Type=\"Text\">North</Value></Eq> <Eq><FieldRef Name=\"Zone\"/><Value Type=\"Text\">South</Value></Eq> </Or> </Where>"; SPListItemCollection stCol = stateList.GetItems(stateQuery); Now, to increase the complexity we could think of a query which will filter out all the states starting with 'M' and belonging to West / East zone. stateQuery.Query = "<Where> <And> <BeginsWith><FieldRef Name=\"Title\"/><Value Type=\"Text\">M</Value></BeginsWith> <Or> <Eq><FieldRef Name=\"Zone\"/><Value Type=\"Text\">East</Value></Eq> <Eq><FieldRef Name=\"Zone\"/><Value Type=\"Text\">West</Value></Eq> </Or> </And> </Where>"; SPListItemCollection stCol = stateList.GetItems(stateQuery);