How to: Work with the SPQuery

The SPQuery will be in Caml format. You can use one to get a collection of items from a list.

For example,

SPListItemCollection results = listName.GetItems(query);

The above will get a subcollection of items from the listName list, according to the query inside the “query”.

In my case, I was looking to implement a Search mechanism that would search the list for “any” of the inserted keywords. The caml query would be:

<Where><Or><Or><Contains><FieldRef Name=’Title’/><Value Type=’Text’>insert</Value></Contains><Contains><FieldRef Name=’Abstract’ Nullable=’TRUE’/><Value Type=’Note’>insert</Value></Contains></Or><Or><Contains><FieldRef Name=’Title’/><Value Type=’Text’>tab</Value></Contains><Contains><FieldRef Name=’Abstract’ Nullable=’TRUE’/><Value Type=’Note’>tab</Value></Contains></Or></Or></Where>

The above Caml query will search for all items that have any of the words “insert” or “tab” in either of the fields “Title” or “Abstract”.

It’s not too hard to write a function that creates the above caml query programmatically. However, the U2U Caml Builder will definitely help you when trying to figure out the structure of your query.

NOTE: If you start getting an error saying “One or more field types are not installed properly. Go to the list settings page to delete these fields.” when running your caml query, there are two things to check.

1. Are the fields that you are targetting in your caml query correctly spelt? (in my case, Title and Abstract) and

2. Is you caml query well formatted. It is more probable than not, that you may have gotten the field names correctly but failed to structure your query correctly. The U2U Caml Builder will help you by creating a mock-up query that you can use to build your own according to.

MGR: the Intelogist

About MGR: the Intelogist

SharePoint Server developer, turned Sitefinity developer, turned Angular developer, turned SharePoint Online consultant, turned Unily consultant, turned O365 consultant... Never a dull moment!

One thought on “How to: Work with the SPQuery

  1. […] a previous post, I talked about the SPQuery and the CAML query […]

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

This site uses Akismet to reduce spam. Learn how your comment data is processed.