Translate

Monday, August 20, 2012

Working with CAML Queries and SPQuery

CAML Queries



In sharepoint if we want to retrieve the data from Lists we need to use CAML Queries
CAML stands for Collaberative application markup language,which is basically xml format language query style.

To query the list we need to use SPQuery object by creating new object and assigned the CAML query to SPQuery.Query

CAML Query operators

Operator                Description
And                 It will be used to combined the two or more conditions or multiple conditions
BeginsWith      Searches for a string at the beginning of the text field
Contains         Searches for a string within the text field
Eq                Equal to
FieldRef         A reference to a field (useful for GroupBy elements)
Geq              Greater than or equal to
GroupBy       Groups results by these fields
Gt                 Greater than
IsNotNull      Is not null (not empty)
IsNull            Is null (empty)
Join               Used to query across two lists that are joined through a Lookup field
Leq               Less than or equal to
Lt                  Less than
Neq             Not equal to
Now            The current date and time
Or               Boolean or operator
OrderBy     Orders the results of the query
Today         Today’s date
TodayIso    Today’s date in International Organization for Standardization (ISO) format
Where       Used to specify the Where clause of the query 




the following example will list out all the announcements which are not expired till date,we will be fetching all announcements "Title"

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></today></value>
</fieldref></lt>
</where>";

SPList list = SPContext.Current.Web.Lists.TryGetList("Announcements");
SPListItemCollections items = list.GetItems(query);

Here "items" are announcements title result</fieldref></fieldref>

1 comment:

  1. This post is not working, caml is case sensitive, the entire query is lowercase

    ReplyDelete