Thursday, April 21, 2011

Query a List by using CAML in SharePoint

In this article, we will discuss how to query a SharePoint List using CAML in SharePoint 2010.
Microsoft.SharePoint. SPQuery object has Query property that accepts a CAML fragment, which defines the query to be performed. A ViewFields property defines the fields to return.

Microsoft Flow is very much new and very much useful in SharePoint Online Office 365.

Code Sample:

SPQuery query = new SPQuery;
query.Viewfields = @"<fieldref Name='Title'/><fieldref Name='Expires'/>";
query.Query =
@"<where>
<lt>
<fieldref Name='Expires'/>
<value Type='DateTime'><Today/></Value>
</Lt>
</Where>";
SPList list = SPContext.Current.Web.Lists.TryGetList("Announcements");
SPListItemCollections items = list.GetItems(query);

Each FieldRef element has a Name attribute that specifies the name of the list field to return from the query.

The CAML fragment may contain Where, OrderBy, and GroupBy elements.

<where>
</Where>
<orderby>
<FieldRef/>
</OrderBy>
<groupby>
<FieldRef/>
<groupby>

Where condition may contain: And,BeginsWith,Contains,Eq,FieldRef,Geq,GroupBy,Gt,IsNotNull,IsNull,Join, Leq,Lt,Neq, Now,Or etc
SPQuery object can be used to query across two lists that are joined by a Lookup field.
Showing you a sample from Inside book:

SPWeb site = SPContext.Current.Web;
SPList listInstructors = site.Lists["Instructors"];
SPList listModules = site.Lists["Modules"];
SPQuery query = new SPQuery;
query.Query = "<where><eq><fieldref Name="Audience"/>" +
"<value Type="Text">Developer</Value></Eq></Where>";
query.Joins = "<join Type="Inner" ListAlias="classInstructors">" +
"<eq><fieldref Name="Instructor" RefType="Id" />" +
"<fieldref List="classInstructors" Name="Id" /></Eq></Join>";
query.ProjectedFields =
"<field Name='Email' Type='Lookup' List='classInstructors' ShowField='Email'/>";
query.ViewFields = "<fieldref Name="Title" /><fieldref Name="Instructor" />" +
"<fieldref Name="Email" />";
SPListItemCollection items = listModules.GetItems(query);

I have followed the article from inside SharePoint 2010 book.

No comments:

Post a Comment