views:

366

answers:

1

I have a webpart which is 2-3 subsites down the top level site. I need to query the list which is in top site collection and one at the same level,I guess its possible through SPSiteDataquery...I have some confusion related to it can i write single query which can query both these list....

The scope of this query is sitecollection so that means it wud going to look into all list in sitecollection..and if my CAML query is same for both these lists ...it should work?

let me explain through my code:

SPSite mySite = SPControl.GetContextSite(Context);
                SPWeb myWeb = SPControl.GetContextWeb(Context);
                SPSiteDataQuery qry = new SPSiteDataQuery();
                qry.Lists = "<Lists BaseType='0' />";

                qry.Query = "<Where><Contains><FieldRef Name='Country'/><Value Type='Text'>" + strcount + "</Value></Contains></Where>";

                qry.ViewFields = "<FieldRef Name='Capital' Nullable='TRUE'/><FieldRef Name='Currency' Nullable='TRUE'/>";

                qry.Webs = "<Webs Scope='SiteCollection' />";

                DataTable dt = myWeb.GetSiteData(qry);

Now i need currency from list which is in top level site and Capital from the list which is at same level. Is this possible? or I misunderstood SPSiteDataQuery...?

A: 

You are on the right track and it is possible to retrieve results for lists in different webs. The following example shows how to retrieve items from the default 'Tasks' or 'Workflow Tasks' lists and works with task lists created at the root level and within a sub site.

        SPSiteDataQuery q = new SPSiteDataQuery();
        q.ViewFields = "<FieldRef Name='Title'/><FieldRef Name='Priority'/><FieldRef Name='Status'/>";
        q.Webs = "<Webs Scope='SiteCollection' />";
        q.Lists = "<Lists BaseType='0' />";
        q.Query = "<Where><Gt><FieldRef Name='ID' /><Value Type='Number'>0</Value></Gt></Where>";

        DataTable results = new DataTable();

        using (SPSite site = new SPSite("http://sharepoint"))
        {
            using (SPWeb web = site.OpenWeb("subsite"))
            {                    
                results = web.GetSiteData(q);
            }
        }

I've written it using a hardcoded URL so you can run it inside a console application for testing but you can replace the using statements with something like SPWeb web = SPContext.Current.Web; when you put this inside a web part.

A few other things worth considering:

  • The lists you are querying must contain all the fields in the ViewFields element
  • Multi-lookup fields do not work well with the SPSiteDataQuery (single value lookup fields are ok)
  • The u2u CAML builder tool is also useful for testing CAML queries. See http://www.u2u.be/Res/Tools/CamlQueryBuilder.aspx
Ari