Complex CAML queries made simple
by Hojo Clement • February 11, 2011 • MOSS 2007 • 4 Comments
Update: If you want a quicker solution, please check out my new CAML Viewer Web Part for SharePoint 2010.
In this post we will see how we can generate complex CAML queries easily. We will also see how we can use this query to fetch data from the list.
If you want to create a complex query, first create a list view based on the required criteria. Then use the below code to get the query.
SPWeb web = SPControl.GetContextWeb(this.Context); SPList spList = web.Lists["Mylist"]; SPView view = spList.Views["Myview"]; Response.Write(view.Query.ToString());
Once we have this CAML query we can easily extract data from SharePoint list. Below is the code to fetch data from SharePoint list using CAML query
SPQuery query = new SPQuery();
query.Query = view.Query.ToString();
SPListItemCollection cole = spList.GetItems(query);
foreach (SPListItem item in cole)
{
Response.Write(item["Title"] +"<br />");
}

I love the tactic. I use SharePoint Designer as my code generator too. It’ll get me all the way there 90% of the time. I also have a different way of creating my complex CAML queries. I’d love for you to look it over…
http://mattbramer.blogspot.com/2011/02/in-response-to-complex-caml-queries.html
Cheers,
Matt
Pingback: SharePoint Daily » Blog Archive » Open Government on SharePoint; Windows Will Change; Why I’m Sticking With Chrome
Pingback: Open Government on SharePoint; Windows Will Change; Why I'm Sticking With Chrome - SharePoint Daily - Bamboo Nation
Pingback: CAML Viewer Web Part – All about MOSS