Sharepoint : Query multiple list from multiple site in a site collection.

 SPSiteDataQuery class

Use SPSiteDataQuery class to fetch data across multiple list in multiple sub sites within a site collection.Below snippet shows about how do we use it.This class makes you a smart developer instead of looping all the sub sites.

You can use an instance of this class to retrieve data from selected lists or from all lists in the current site collection. Specify the scope of the query by setting the Websproperty. Specify the lists to participate in the query by setting the Lists property and the fields to return by setting the ViewFields property. Control data selection and order by setting the Query property.

         SPWeb web = SPContext.Current.Web;
         SPSiteDataQuery query = new SPSiteDataQuery();

         //Ask for all lists created from the contacts template.
         query.Lists = "<Lists ServerTemplate=\"105\" />";

         // Get the Title (Last Name) and FirstName fields.
        query.ViewFields = "<FieldRef Name=\"Title\" />" +
                          "<FieldRef Name=\"FirstName\" Nullable=\"TRUE\" Type=\"Text\"/>";
        // Note that setting the Nullable attribute to TRUE
        // causes an empty value to be returned for lists that
        // do not include the FirstName column. The default is 
        // to skip a list that does not include the column.

         // Set the sort order.
         query.Query = "<OrderBy>" + 
                           "<FieldRef Name=\"Title\" />" + 
                       "</OrderBy>";

         // Query all Web sites in this site collection.
         query.Webs = "<Webs Scope=\"SiteCollection\" />";

         DataTable dt = web.GetSiteData(query);


The Webs property specifies which Web sites to include in the query. By default, the query considers only the Web site from which the GetSiteData method was invoked.
You can broaden the scope of the query by setting the Webs property to a string containing a Webs tag and a Scope attribute. Possible values of the Scope attribute include Recursive and SiteCollection.
<Webs Scope="Recursive" />
<Webs Scope="SiteCollection" />
When the Scope attribute is set to Recursive, the query considers the current Web site and all subsites of the current Web site.
When the Scope attribute is set to SiteCollection, the query considers all Web sites that are in the same site collection as the current Web site. Of the two attribute values, this is the more inclusive.

Comments

Popular posts from this blog

Sharepoint 2013-Minimal Download Strategy.

Bulk update and delete using SPservice in SharePoint