SharePoint 2003: Some example CAML queries

In SharePoint you are not supposed to directly access the database. Instead you should access data via the object model. SharePoint has its own syntax for queries named CAML (Collaborative Application Markup Language).
Example query filtering by a boolean field

<Where>
   <Eq>
      <FieldRef Name="IsCurrent"/>
      <Value Type="Boolean">1</Value>
   </Eq>
</Where>

Example query bounded by a date

<Where>
   <Leq>
      <FieldRef Name="Created" />
      <Value Type="DateTime">1979-05-05T00:00:00Z</Value>
   </Leq>
</Where>

Example query across a date range
Note that the “and” node has to wrap around both conditions. There is no “and”clause in-between the conditions (i believe that this is also true with an “or” statement).

<Where>
   <And>
      <Geq>
         <FieldRef Name="Created" />
         <Value Type="DateTime">2006-07-20T00:00:00Z</Value>
      </Geq>
      <Leq>
         <FieldRef Name="Created" />
         <Value Type="DateTime">2007-07-20T00:00:00Z</Value>
      </Leq>
   </And>
</Where>

Example query across a date range with an additional clause
Note that the “and”clause can only wrap two conditions. If you need to use any more, you will need to use multiple “and”nodes – see example below:

<Where>
   <And>
      <And>
         <Geq>
            <FieldRef Name="Created" />
            <Value Type="DateTime">2006-07-20T00:00:00Z</Value>
         </Geq>
         <Leq>
           <FieldRef Name="Created" />
           <Value Type="DateTime">2007-07-20T00:00:00Z</Value>
         </Leq>
      </And>
      <Eq>
         <FieldRef Name="ID" />
         <Value Type="Counter">1</Value>
      </Eq>
   </And>
</Where>

Note that when running a query through the object model, you may need to wrap “<Query>” around the query (im pretty sure that this isnt the case though).
Also – highly recommended is the camlbuilder available at http://www.u2u.info/SharePoint/U2U%20Community%20Tools/Forms/AllItems.aspx

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>