• Complex CAML queries made simple

    by  • 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 />");
    }
    

    About

    Hojo Clement was working in US Technology in Trivandrum as a Senior Software Engineer. He hasĀ 6 years experience in working with Web Development Technologies inlcuding MOSS and ASP.net.

    4 Responses to Complex CAML queries made simple

    1. February 11, 2011 at 12:43 am

      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

    2. Pingback: SharePoint Daily » Blog Archive » Open Government on SharePoint; Windows Will Change; Why I’m Sticking With Chrome

    3. Pingback: Open Government on SharePoint; Windows Will Change; Why I'm Sticking With Chrome - SharePoint Daily - Bamboo Nation

    4. Pingback: CAML Viewer Web Part – All about MOSS

    Leave a Reply

    Your email address will not be published. Required fields are marked *