SPQuery Examples

Related Post : Spquery in Sharepoint 2010 – Tutorial

Basic Query - Query to get all the Items from a list where Category field is equal to "Sp2007"

// Get SiteColl
SPSite curSite = new SPSite("http://myPortal");

//Get Web Application
SPWeb curWeb = curSite.OpenWeb();

// Create a SPQuery Object
SPQuery curQry = new SPQuery();

//Write the query (I suggest using U2U Query Bulider Tool)
curQry.Query = "<Where><Eq><FieldRef Name='Category' />
<Value Type='Text'>
SP2007 </Value></Eq></Where>";

// Set the Row Limit
curQry.RowLimit = 100;

//Get the List
SPList myList = myWeb.Lists["ListName"];

//Get the Items using Query
SPListItemCollection curItems = myList.GetItems(curQry);

// Go through the resulting items
foreach (SPListItem curItem in curItems)
{
string ResultItemTitle = curItem["Title"].ToString();
}

Query on DateTime Field - Query to Find Items in the List with Today's date.

// Create a SPQuery Object
SPQuery DateFieldQuery = new SPQuery();


//Write the query (I suggest using U2U Query Bulider Tool)
DateFieldQuery.Query = “<Where><Eq><FieldRef Name=\ ”TodaysDate\” />
<Value Type=\ ”DateTime\”> + DateTime.Now.ToString("yyyy-MM-ddTHH:\\:mm \\:ssZ") + </Value>
</Eq></Where>”;

//Get the List
SPList myList = myWeb.Lists["ListName"];

//Get the Items using Query
SPListItemCollection ResultItems = myList.GetItems(DateFieldQuery);


Query Using Yes\No Columns -
Query to Retrieve all the Items from a list where a Yes\NO type Field, named "AreYouCool?" is "Yes".


// Create a SPQuery Object
SPQuery CheckBoxQuery = new SPQuery();


//Write the query (I suggest using U2U Query Bulider Tool)
CheckBoxQuery .Query = “<Where><Eq><FieldRef Name=\ ”AreYouCool?\” />
<Value Type=\ ”bit\”>1</Value>
</Eq></Where>”;

//Get the List
SPList myList = myWeb.Lists["ListName"];

//Get the Items using Query
SPListItemCollection ResultItems = myList.GetItems(CheckBoxQuery);

Related Post :Related Post : Spquery in Sharepoint 2010 – Tutorial

0 comments:

Post a Comment

Disclaimer

This is a personal weblog. The opinions expressed here represent my own and not those of my employer or anyone else. Should you have any questions or concerns please e-mail me at sharepointprogrammingblogger@gmail.com .

Copyright (c) 2010 @ myshaepointwork.blogspot.com. All rights are reserved.Do Not Copy.

@ Learning SharePoint.com