Sunday, December 17, 2006

CAML Queries return all items despite of filter

This had me puzzled for a while, so let me spare you the agony.

I was writing code that queried a list using the GetListItems function of the SPList object. The query I was using was from the U2U Caml Creator (great application, even with the bugs) and was working on that application perfectly - filtering my list to return only the items I wanted.
But in my web part the query would return all items in the list, ignoring the filter I set.

After some tests I found the problem. Apperantly the SPQuery object automatically wraps your query with the "<query>" tag, and since the U2U Caml Creator application also generates queries with the "<query>" tag, you actually have two "<query>" tags in your query, which makes sharepoint ignore the filters you set in the query.

So next time you are using the SPQuery object, remember the Query property should receive a CAML query, but without the "<query>" tag. Only whats under it.


Geronimo said...

Hehe, I know this one too ;-)
I also blogged it:

SPHuman said...

Thanks for this. You will not believe how much time I spent trying to figure out why my CAML query with Query tags on both ends with a SPQuery object did not work.

rebecca said...

thanks so much! i can go home now.

Jose said...

Thank You very Much!!! I was going crazy with CAML working in the tools and not with my Web Part.
"What A Query..."

Anonymous said...

thanks buddy.