2007-04-17

Creating and using CAML Queries

To query SharePoint for data you need to write CAML queries. Complex queries are not easy to write, and therefore you are in a strong need for good tools. Lucky for you AND me there are a couple of these around which you just have to have:

  • U2U Caml Builder - on the web. Link here.
  • STAMIT's Caml Viewer - on CodePlex. Link here.
  • Tips & tricks working with CAML queries. MSDN article ; Operators s null = IsNull, is not null = IsNotNull, etc.

Those 2 tools are good companions. Without tools like these writing the right queries is an error prone challenge, but now .... its much simpler and quicker!

A simple CAML query that is easy to write, but even easier to extract using the mentioned tools:

System.Text.StringBuilder sbQuery = new
System.Text.StringBuilder();

sbQuery.Append(" <OrderBy>");
sbQuery.Append(" <FieldRef Name=\"Sortering\" />");
sbQuery.Append(" </OrderBy>");
sbQuery.Append(" <Where>");
sbQuery.Append(" <Neq>");
sbQuery.Append(" <FieldRef Name=\"Page_ID\" />");
sbQuery.Append(" <Value Type=\"Number\">" + properties.ListItem["ID"].ToString()
+ "</Value>");
sbQuery.Append(" </Neq>");
sbQuery.Append(" </Where>");

string sResult = sbQuery.ToString();
SPQuery q = new SPQuery();
q.Query = sResult;

SPListItemCollection val = list.GetItems(q);

Using IsNotNull:

sbQuery.Append(" <Where>");
sbQuery.Append(" <IsNotNull>");
sbQuery.Append(" <FieldRef Name=\"MyField\" />");
sbQuery.Append(" </IsNotNull>");
sbQuery.Append(" </Where>");

No comments: