SPQuery returning all items 

If you've ever used the SPQuery objects to get SPListItems from a SPList, and you didn't get it to work because the query would return ALL items in the SPList, you might have used code similar to this:

SPQuery postsQuery = new SPQuery();
postsQuery.Query = string.Format(
    "<Query>"+
       "<OrderBy>"+
          "<FieldRef Name='Created' />" +
       "</OrderBy>"+
       "<Where>"+
          "<Eq>"+
             "<FieldRef Name='ThreadID' />"+
             "<Value Type='Number'>{0}</Value>"+
          "</Eq>"+
       "</Where>"+
    "</Query>", threadID);

SPList allPosts = SpecificForumData.GetPostList(); // Custom method to get the SPList object
SPListItemCollection posts = allPosts.GetItems(postsQuery);

I've always built my queries by hand (what better way to learn than trial and error, right?), but when I tried the U2U CAML Query Builder to construct my SPQuery it suddenly all failed, and all items in the SPList was returned.

To solve this issue, just remove the <Query> and </Query> tags from the generated query that U2U CAML Query Builder produces and it should all work again.

So, replace the above code with this:

SPQuery postsQuery = new SPQuery();
postsQuery.Query = string.Format(
       "<OrderBy>"+
          "<FieldRef Name='Created' />" +
       "</OrderBy>"+
       "<Where>"+
          "<Eq>"+
             "<FieldRef Name='ThreadID' />"+
             "<Value Type='Number'>{0}</Value>"+
          "</Eq>"+
       "</Where>", threadID);

SPList allPosts = SpecificForumData.GetPostList(); // Custom method to get the SPList object
SPListItemCollection posts = allPosts.GetItems(postsQuery);

If all is well, you should now be able to run this query to get better performance AND return only the selected SPListItem objects from the SPList

Edit: As a result of Peter's comment, I'd also like to mention that the RowLimit of an SPQuery object is set to 100 per default, so if you do not alter the .RowLimit property you'll end up with a result set of maximum 100 items. Thanks Peter

Hope it helps someone :)

 
Posted on 2-May-08 by Tobias Zimmergren
4 Comments  |  Trackback Url  |  Link to this post | Bookmark this post with:        
Tags: CAML, Queries
 

Links to this post (Trackbacks/Pingbacks)

Comments

Friday, 2 May 2008 05:16 by Peter
One other thing to note, the query.RowLimit property is set by default to 100 items. If you fail to set it to something higher, guess what! Yep, hope your list doesn't grow "too large", i.e. above 100 items! Anyway the RowLimit thing is a big gotcha as well, and has bitten me in the past.

Friday, 2 May 2008 06:39 by Tobias Zimmergren
Great tip Peter, didn't think of that!

Name:
URL:
Email:
Comments:


MCTS WSS 3.0 (Developer and Administration/Configuration) MCTS MOSS 2007 (Developer and Administration/Configuration) MCP