Saturday, March 21, 2015

Get multiple List data across multiple sites using SPSiteDataQuery in Sharepoint 2013


Scenario:  you want to display data from multiple list spread across multiple site inside the site collection.


Solution : SPSiteDataQuery to query across the site with web scoped at SiteCollection.


Example to explain this : 

Set Up :  

I have one site collection with two subsites

1. ProjectSubsite1 with List named as IssueList


Now i want to aggregate these two list data and display in web part on top level site collection , this cannot be possible with SPQuery hence we will be using SPSiteDataQuery as shown below 

Properties to set
1. Query :  you need to mention your condition in caml query format 
2. List : you need to mention List Servertemplate Id , hence data will be fetched from those list types
3. ViewFields : no of fields to be fetched for diplay
4. Webs : here you have to mention Site Collection so that search is triggered across complete site collection.

once SPSiteDataQuery object is formed pass the object to method web.GetSiteData this return datatable 

using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = site.OpenWeb())
{
SPSiteDataQuery query = new SPSiteDataQuery();

query.Lists = "<Lists ServerTemplate=\"100\" />";

query.Query
= "<Where><Eq><FieldRef Name='ContentType' /><Value Type='Text'>IssueCT</Value></Eq></Where>";

query.ViewFields = "<FieldRef Name='Title' />";

query.Webs = "<Webs Scope=\"SiteCollection\" />"; 

DataTable dt = web.GetSiteData(query);

}
 }


Limitation : SPSiteDataQuery will run only across particular site collection.








No comments:

Post a Comment