How to simulate the SQL WHERE IN clause in a SPQuery

Simulate a WHERE IN clause in a SPQuery

If you ever have used something like


in T-SQL, and wanted to mimic this functionality in the SharePoint SPQuery class, you probably have found out there is no IN statement in the CAML Query language.
So what do do? Here’s a way to simulate WHERE IN clause in a SPQuery statement.

One solution is to use a LinQ query that looks something like this:

However, this has a serious performance problem. Because the .AllItems property will do a full T-SQL select all items behind the scenes, it can get very slow if you have thousands and thousand of items in your list.
It do look elegant, however.

Another way is to build up a CAML query that does an OR statement for every item that you have in your list of values.
Essentially, you will have to build up something that looks similar to this CAML query:


Notice that the CAML syntax for multiple OR statements is a little bit odd. You would at first glance think that is would look like this:

But this will throw an error. You will need to have nest the OR statements within each other.

For this purpose I have written a small helper method that will build the CAML query for a given list of values in a List of strings.
You call it like this:

The first parameter is the field that you want to comapre on, the second parameter is the type (“Eq” makes most sense in this scenario), and the third parameter is of List of strings.
Here’s the code for the helper method:

Using UserMulti field in the CAML schema

This was unexpected, and not documented at all in the SharePoint SDK.

When you create a UserMulti column, you must also specify Mult=”TRUE”, otherwise it will fall back to a standard (single select) User column type.

<Field ID=”{12312312-1234-1234-1234-123412341234}”

Group=”My Group”