As a sharepoint developer most of the people might have used SPQuery and CAML atleast once.
Writing a Basic Query
SPContext ctx = SPContext.Current;
using (SPSite site = new SPSite(ctx.Site.ID))
{
using (SPWeb web = site.OpenWeb(webid))
{
SPList list = web.Lists["MyTestList];
SPQuery query = new SPQuery();
//You have to call GetItems function of SPlist to execute the CAML query
SPListItemCollection items = list.GetItems(query);
}
}
Here it will return All the Items.But in real time we need to specify the conditions and attributes to fine tune the Results. We need to have basic understanding of CAML syntax inorder to take full advantage of SPQuery Object.If you have a CAMLBuilder tool then it will be always handy in writing CAML queries.You could douwnload CAML builder from here
Understanding SPQuery Properties
1. SPQuery.RowLimit
This Property allows you to set how many rows you need in your result.Its quiet common that your Query could return more than 500 rows so its better to limit the number of rows in a result and use paging to retrive the rest of the result.I will explain paging below.
2. spquery.ViewAttributes
View attribute is one of the important attribute which is veryusefull to set how you are going to retrieve the Data.
Scenario 1: You want retrieve all the items including items in folder and subfolders then set it like the following
//If you want to return only file
SPQuery.ViewAttributes = "Scope='Recursive'"; //If you want to return All items
SPQuery.ViewAttributes = "Scope='RecursiveAll'";
Scenerio 2 : You want retrive only files
spquery.ViewAttributes = "Scope=\"FilesOnly\"";
Scenario 3: Only Approved Items
spquery.ViewAttributes = "ModerationType='HideUnapproved'"
3. SPQuery.Folder
This property is usefull when you want to retrieve the data only from specific folder.In real world scenario you need to retrive the items from specific folder rather than retrieving all items in the list.
SPQuery.Folder = folder; //It should be a SPFolder Object
4.SPQuery.ViewFields

Join the conversation! Your thoughts help the community grow.