Search This Blog

Wednesday, May 18, 2016

Cross Site List Query using SPSiteDataQuery in SharePoint 2013

SPSiteDataQuery can be used to perform cross-site and cross-list queries. In order to use it, you must call SPWeb.GetSiteData method on the appropriate web and provide a SPSiteDataquery object.

We can use this class to retrieve data from selected lists or from all the lists in the current site  collection. We have to set the following before we start.

  • Specify the scope of the query by setting the Webs property (Site collection, site etc). 
  • Specify the lists to participate in the query by setting the Lists property 
  • Specify the fields to return by setting the View Fields property. 
  • We have to Control data selection and order by setting the Query property.


SPSiteDataQuery and SPQuery differ SPSiteDataQueries ability to search more than a single site or single list. SPSiteDataQuery can be configured to search in all lists of a particular list type or list base type located in either

1) The complete site collection

2) a particular site and sub-sites

Using SPSiteDataQuery.Webs property you can specify where the data will be retrieved from. This property can have one of the following values:

“” (or string.Empty) – default value : will search only the SPWeb on which you run GetSiteData

“<Webs Scope=’SiteCollection’ />” : will search on all webs in the site collection

“<Webs Scope=’Recursive’ />” : will search the SPWeb on which you run GetSiteData and all subwebs

You can restrict the search using Lists and Query properties. In the following example we query all contacts lists in the site collection for items containing John in the Last Name field:SPSiteDataQuery query = new SPSiteDataQuery();

//query contacts list.

query.Lists = “<Lists ServerTemplate=’105′ />”;

query.ViewFields = “<FieldRef Name=’Title’ />”;

query.Query = “<Where><Contains>” +

“<FieldRef Name=’Title’ /><Value Type=’text’>John</Value>”+

“</Contains></Where>”;

query.Webs = “<Webs Scope=’SiteCollection’ />”;

DataTable dt = SPContext.Current.Web.GetSiteData(query);

For the Lists property you can use constructs like:

<Lists ServerTemplate=’10001′ /> – query lists with template 10001

<Lists BaseType=’5′ /> – Issues lists

<Lists><List ID=”960BF6F6-F264-4305-B3CB-BDB9BF8F67DF” /></Lists> – query a specific list

No comments:

Post a Comment