When is a Query not a Query?

The answer? In SharePoint when you use the word "Query".

I recently used a tool entitled "U2U CAML Query Builder and Execution tool". Don't take this as a recommendation of this tool, its rough round the edges but it does what it says on the tin.

You can use this tool to connect to your SharePoint site, drill in to your SPList and, using a pre-populated choice of fields in your list, construct a CAML query.

U2U

You can test your queries from here too.

I was using it to generate the query I needed to add to my code:

private static SPListItemCollection GetIncompleteTasks(SPList taskList)
        {
            SPQuery query = new SPQuery();
            query.Query = @"<Query><Where><IsNull><FieldRef Name='CompletionDate' /></IsNull></Where></Query>";
            return taskList.GetItems(query);
        }

However, there is a well hidden deceitful gotcha here. If you use the Query tag in your SPQuery.Query string it totally negates the rest of your query!. In this case it ignores the where clause and will always return the entire contents of the list.

This seems very misleading to me. If the CAML is malformed I would have anticipated an exception to be thrown so developers could know to remove the <Query> tag. The other alternative is to detect and ignore this tag, or worse case don't return any results. But to pretend to work and return all records!?

Resolution, remove <Query>:

private static SPListItemCollection GetIncompleteTasks(SPList taskList)
        {
            SPQuery query = new SPQuery();
            query.Query = @"<Where><IsNull><FieldRef Name='CompletionDate' /></IsNull></Where>";
            return taskList.GetItems(query);
        }

Comments

# re: When is a Query not a Query?
Gravatar Hi Neil,
I know it is not clearly mentioned by the U2U CAML Query Builder but the tags are only needed when you work with the GetListItems method of the Lists web service. For the rest, the query is the same. This will become more clearly when the tool generates code samples instead of pure CAML.
I appoligize for the confusion.
Karine Bosch
Developer of the U2U CAML Query Builder
Left by Karine Bosch on 11/15/2008 8:09 PM
# re: When is a Query not a Query?
Gravatar Thanks Karine,

My criticism is more directed at the SharePoint API than U2U CAML Query Builder. Not only does this reflect the lack of consistency found in the SharePoint API but Sharepoint should throw an exception when the Query tags are there. To just return everything suggests the query is valid.

I look forward to the CodeGen ;-)

Neil.
Left by njenman on 11/19/2008 4:18 PM

Leave Your Comment

Title*
Name*
Email (never displayed)
 (will show your gravatar)
Url
Comment*

Please add 3 and 4 and type the answer here:

Preview Your Comment.