Composing multiple criteria CAML Queries

OK, so I’ve been writing a pile of CAML queries recently.

Now there is the fantastic U2U CAML Query Builder tool which you can use to write your CAML for you, however I’m from the school of though that I like to know how to do it myself even if I do use the tools, I guess that is where my habit of pulling things apart to see how they work stems from.

Edit: It turns out that the CAML query builder tool doesn’t allow more than 2 criteria.

Anyway. the rules for composite criteria CAML are pretty simple. Essentially you can apply a logical operator to any two criteria and criteria may also be composed of results of logical operations.

So, what does this mean in CAML? Let’s say we want to find items for a given project and student that have been sent.:

<Query>
	<Where>
		<And>
			<And>
				<Eq>
					<FieldRef Name="StudentId" />
					<Value Type="Text">{0}</Value>
				</Eq>
				<Eq>
					<FieldRef Name="ActivityId" />
					<Value Type="Text">{1}</Value>
				</Eq>
			</And>
			<Eq>
				<FieldRef Name="HasBeenSent" />
				<Value Type="Boolean">TRUE</Value>
			</Eq>
		</And>
	</Where>
</Query>

Of course you would replace {0} and {1} with the values that you were seaching for.

Now let’s say that we want the items that either have a Pending status or have been sent for a given student:

<Query>
	<Where>
		<And>
			<Or>
				<Eq>
					<FieldRef Name="HasBeenSent" />
					<Value Type="Boolean">TRUE</Value>
				</Eq>
				<Eq>
					<FieldRef Name="Status" />
					<Value Type="Text">Pending</Value>
				</Eq>
			</Or>
			<Eq>
				<FieldRef Name="StudentId" />
				<Value Type="Text">{0}</Value>
			</Eq>
		</And>
	</Where>
</Query>
Advertisements
This entry was posted in CAML, SharePoint. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s