Search This Blog

Saturday, September 12, 2015

How to create a Dynamic CAML Query

Many a times you might come into a situation when you have to deal with some complex query building and 

the scenario is like you have to pull the data from a SharePoint list and the records on which you need to fire 
the <Where> clause is not fixed.

So, you to need to write a dynamic query where the <OR> tags changes accordingly.
Here is the code:

// This lstPeers can be of any type like array or List Type or Collection.
List<String> lstPeers = new List<String>();

SPQuery peersQuery = new SPQuery();
string createquery = "";
peersQuery.Query = "<Where>" + CreateDynamicQuery(createquery, lstPeers) 
+ "</Where>";


Here is your Dynamic Query :

protected String CreateDynamicQuery(String query, List<string> lstString)
        {
            bool firstIteration = true;
            if (query != "")
            {
                query = "<Or>" + query;
                firstIteration = false;
            }

            if (lstString.Count >= 2)
            {
                query += "<Or>";
                query += "<Eq><FieldRef Name='Type' /><Value Type='Lookup'>"
                + lstString[0] + "</Value></Eq>";
                query += "<Eq><FieldRef Name='Type' /><Value Type='Lookup'>" 
                 + lstString[1] + "</Value></Eq>";
                query += "</Or>";

                lstString.RemoveRange(1, 1);
                lstString.RemoveRange(0, 1);

                if (!firstIteration)
                    query += "</Or>";

                if (lstString.Count != 0)
                    query = CreateDynamicQuery(query, lstString);
            }
            else
            {
                if (lstString.Count != 0)
                {
                    query += "<Eq><FieldRef Name='Type' /><Value Type='Lookup'>" 
                  + lstString[0] + "</Value></Eq>";
                    if (!firstIteration)
                        query += "</Or>";
                }
            }
            return query;
        }


As you can notice you are calling a recursive function and dynamically creating the <OR> tags.


No comments:

Post a Comment