Question

I'm using SPSiteDataQuery to query several lists in different sites. Unfortunately, I don't want the data from all of these sites; I have a list of ones to include and exclude.

So far I've seen SPSiteDataQuery.Webs which seems to only allow the scope to be changed (entire collection, just subsites, just this site), and SPSiteDataQuery. Lists which would require the List IDs (that I don't have) or the lists' template IDs (not specific enough).

How do I persuade SPSiteDataQuery to only return results for the sites on my include list? FYI: I have the IDs and URLs of the sites to include, and filtering post-fetch is not an option.

Was it helpful?

Solution

I don't think you can do this without some form of filtering post fetch. However, it isn't hard.

SPSiteDataQuery queries automatically include DataColumns in the DataTable for ListId and WebId, so you could then filter your DataTable by Web. I know it's not idea - 'query and filter', rather than just 'query' - but it should work.

The following queries for all documents with ID=1, and then filters to a particular Web. I guess your filter expression would be more complicated.

        using (SPSite site = new SPSite(url))
        {
            using (SPWeb web = site.OpenWeb())
            {
                SPSiteDataQuery q = new SPSiteDataQuery();
                q.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Integer'>1</Value></Eq></Where>";
                q.Webs = "<Webs Scope='SiteCollection' />";
                q.Lists = "<Lists BaseType=\"1\" />";
                q.ViewFields = "<FieldRef Name='ID' /><FieldRef Name='FileLeafRef' />";

                DataTable table = web.GetSiteData(q);
                DataRow[] filteredRows = table.Select("WebId = '{282625A8-B13B-4DC0-B62E-D3255011FB5C}'");
                foreach (DataRow row in filteredRows)
                {
                    foreach (DataColumn col in table.Columns)
                    {
                        string colData = string.Empty;
                        if (row[col] != null)
                        {
                            colData = row[col].ToString();
                        }
                        Console.WriteLine("{0} : {1}", col.ColumnName, colData);
                    }
                }
            }
        }

OTHER TIPS

You can add hidden field with SiteId to each list and use it in query. Dont forget to set data to this field in event recievers.

CrossListQueryInfo\SPSiteDataQuery how to skip items with specific WebId?

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top