foo-baar
foo-baar

Reputation: 1104

Dynamically create CAML query

I have a serach page which earlier was function on SQL DB but now we moved the back-en to SharePoint, I am trying to build a query based upon user select from drop-down box.

Existing SQL query was :

string SQLquery "Select companyname,phone,email from Tab where Approved = 1"

If (country.selectedindex != "")
{
   SQLquery += "AND (country LIKE '%" + country.SelectedValue + "%')"
}
If (functional.selectedindex != "")
{
   SQL += "AND (country LIKE '%" + country.SelectedValue + "%')"
}
If (state.selectedindex != "")
{
   SQL += "AND (state LIKE '%" + state.SelectedValue + "%') OR ( businessareaState like '%" + state.SelectedValue + "%'))"
}

This was easy, but I have to create the same query in CAML based upon user selection form the drop-down lists. Somehow I am not able to give it a dynamic shape since the structure changes completely in the CAML as soon as you add and criteria in it.

Help would be highly appreciated.

Upvotes: 4

Views: 4620

Answers (2)

Avinash
Avinash

Reputation: 121

I have developed C# code to build dynamic query. Its like this

 public string GenerateQuery(IList<CamlQueryElements> lstOfElement)
    {
        StringBuilder queryJoin = new StringBuilder();
        string query = @"<{0}><FieldRef Name='{1}' /><Value {2} Type='{3}'>{4}</Value></Eq>";
        if (lstOfElement.Count > 0)
        {
            int itemCount = 0;
            foreach (CamlQueryElements element in lstOfElement)
            {
                itemCount++;
                string date = string.Empty;
                // Display only Date
                if (String.Compare(element.FieldType, "DateTime", true) == 0)
                    date = "IncludeTimeValue='false'";
                queryJoin.AppendFormat(string.Format(query, element.ComparisonOperators,
                                element.FieldName, date, element.FieldType, element.FieldValue));

                if (itemCount >= 2)
                {
                    queryJoin.Insert(0, string.Format("<{0}>", element.LogicalJoin));
                    queryJoin.Append(string.Format("</{0}>", element.LogicalJoin));
                }
            }
            queryJoin.Insert(0, "<Where>");
            queryJoin.Append("</Where>");
        }
        return queryJoin.ToString();
    }

IList lstOfElement is custom object which holds filter elements. You can create your own object and pass into this method.

Upvotes: 3

Ryan
Ryan

Reputation: 24432

You can use this free tool to help build your CAML queries

http://www.u2u.be/res/tools/camlquerybuilder.aspx

Do a few variations on your query and you will see how the structure changes. Basically you will have to build up an XML document rather than use string concatenation (though that can work as well, it will probably be simpler to build it in an XML parser)

Upvotes: 2

Related Questions