This topic has not yet been rated - Rate this topic

SPWeb.GetSiteData Method

Gets the list items across multiple lists, which can be located in multiple websites in the same website collection.

Namespace:  Microsoft.SharePoint
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)
Available in Sandboxed Solutions: Yes
Available in SharePoint Online
public DataTable GetSiteData(
	SPSiteDataQuery query
)

Parameters

query
Type: Microsoft.SharePoint.SPSiteDataQuery
A query to perform, specifying which websites and lists participate, which fields to return, and the Where and OrderBy sections to apply.

Return Value

Type: System.Data.DataTable
The result of the query.
Exception Condition
ArgumentNullException

The query parameter is null reference.

Each DataRow object in the DataTable.Rows collection represents a single item that satisfies the requirements of the query. Each DataColumn object in the DataTable.Columns collection represents a field that is requested in the query fields, and the column name of the field equals the value of the Name attribute for that field. In addition, DataTable.Columns contains a DataColumn named ListId, which identifies the list that contains each item; a DataColumn named WebId, which identifies the website that contains each item; and a DataColumn named ID, which identifies each item.

The following example is a console application that queries all Tasks lists in a site collection. The query string selects tasks that are assigned to the current user, ordered by date due. After the results are returned, the application prints a report to the console.

using System;
using System.Data;
using Microsoft.SharePoint;

namespace Test
{
   class ConsoleApp
   {
      static void Main(string[] args)
      {
         using (SPSite site = new SPSite("http://localhost"))
         {
            using (SPWeb web = site.OpenWeb())
            {
               SPSiteDataQuery query = new SPSiteDataQuery();

               // Get IDs for all fields used in the query.
               string assignedToId = SPBuiltInFieldId.AssignedTo.ToString("B");
               string taskDueDateId = SPBuiltInFieldId.TaskDueDate.ToString("B");
               string titleId = SPBuiltInFieldId.Title.ToString("B");
               string taskStatusId = SPBuiltInFieldId.TaskStatus.ToString("B");
               string percentCompleteId = SPBuiltInFieldId.PercentComplete.ToString("B");

               // Define the data selection.
               string where = "<Where><Eq>";
               where += "<FieldRef ID='" + assignedToId + "' />";
               where += "<Value Type='Integer'><UserID/></Value>";
               where += "</Eq></Where>";

               // Define the sort order.
               string orderBy = "<OrderBy>";
               orderBy += "<FieldRef ID='" + taskDueDateId + "' />";
               orderBy += "</OrderBy>";

               // Set the query string.
               query.Query = where + orderBy;

               // Query task lists.
               query.Lists = "<Lists ServerTemplate='107'/>";

               // Specify the view fields.
               query.ViewFields = "<FieldRef ID='" + titleId + "' />";
               query.ViewFields += "<FieldRef ID='" + taskDueDateId + "' Nullable='TRUE' />";
               query.ViewFields += "<FieldRef ID='" + taskStatusId + "' Nullable='TRUE' />";
               query.ViewFields += "<FieldRef ID='" + percentCompleteId + "' Nullable='TRUE' />";

               // Query all websites in this site collection.
               query.Webs = "<Webs Scope='SiteCollection'>";

               // Run the query.
               DataTable results = web.GetSiteData(query);

               // Print the results.
               Console.WriteLine("{0, -10} {1, -30} {2, -30} {3}", "Date Due", "Task", "Status", "% Complete");
               foreach (DataRow row in results.Rows)
               {
                  // Extract column values from the data table.
                  string dueDate = (string)row[taskDueDateId];
                  string task = (string)row[titleId];
                  string status = (string)row[taskStatusId];
                  string percentComplete = (string)row[percentCompleteId];

                  // Convert the due date to a short date string.
                  DateTime dt;
                  bool hasDate = DateTime.TryParse(dueDate, out dt);
                  if (hasDate)
                     dueDate = dt.ToShortDateString();
                  else
                     dueDate = String.Empty;

                  // Convert the PercentComplete field value to a percentage.
                  decimal pct;
                  bool hasValue = decimal.TryParse(percentComplete, out pct);
                  if (hasValue)
                     percentComplete = pct.ToString("P0");
                  else
                     percentComplete = "0 %";

                  // Print a line.
                  Console.WriteLine("{0, -10} {1, -30} {2, -30} {3, 10}", dueDate, task, status, percentComplete);
               }
            }
         }
         Console.ReadLine();
      }
   }
}
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Explicit SPWebs to getting right results.
I noticed as Thomas, a strange behaviour on this method when calling it in an implicit way the results returned are not the accurate ones. (The method returns less items than expected) Explanation at http://blogs.msdn.com/b/calvarro/archive/2012/01/23/sharepoint-2010-spweb-getsitedata-method-strange-behaviour.aspx
Do not call this method for SPContext.Current.Web object!
Avoid calling this method more than one time for the SPWeb object because in that case method returns the same data two or three o more times, depends of how many times you call the method. Thus you should create a new SPWeb object for every query.

For example, you can place several copies of standard "User Tasks" web part onto some page and then open that page under the user who has no administrator's permissions. You will see that first web part contains correct count of rows, the second contains twice as much, the third - thrice as much, etc.