Common CAML Problem - Query Tags
There's an issue I've seen raised a few times recently by SharePoint Developers. I record it here in the hope that it'll be found in your favorite search engine and you can get on with your afternoon...
You want to run a CAML query in your code, perhaps an AND query, so you get a tool to generate the CAML below;
<Query>
<Where>
<And>
<Eq>
<FieldRef Name='MyColumn1' />
<Value Type='Text'>SomeValue1</Value>
</Eq>
<Eq>
<FieldRef Name='MyColumn2' />
<Value Type='Text'>SomeValue2</Value>
</Eq>
</And>
</Where>
</Query>
Happy with the well formed query you might insert it into code like that below (CAML not included for brevity);
SPList MyList = myWeb.Lists["MyList"];
string camlquery = "Query String as Above";
SPQuery qry = new SPQuery();
qry.Query = camlquery;
qry.ViewFields = "<FieldRef Name='Title' /><FieldRef Name='Description' />";
You run the query, and in this particular case you become confused because the AND clause never works. This particular example will always return results even when the AND clause doesn't match. Similar examples might not return results at all. When up against a deadline such confusing behavior is most unwelcome.
The problem is simply the inclusion of the <Query> element!
When you write code like this;
qry.Query = camlquery;
The Query property on the object is effectively taking care of the <Query> element for you. Keeping the QUERY element in your own CAML is not handled by the object, and your CAML fails to parse correctly. Take out <Query> and </Query> and the rest of the CAML is well formed and will work.
A small error, but a common one it seems. Hope this helps someone.
Happy SharePointing!