Wednesday, May 30, 2007

Cross List Queries WSSv3 & MOSS 2007

Heya folks,

I've blogging like a bandit lately so this is another one I'd like to cover before hitting the sack :)

SharePoint cross list querying is an easy way to query multiple lists in a particular site for relevant some sort of relevant piece of information. I won't be getting to in detail with this one, but I'll definitely do my best to cover the basics.

A cross list query begins with a "SPSiteDataQuery" object, that's a mouthful. This object like the "SPQuery" object takes in a caml query along with other caml based parameters as arguments. Using this object it's possible to query objects based on list template id's, fields, and field values. It's very common to see this object used to build queries that initiate a "JOIN" operation across lists. This small example shows how we can use this object to retrieve a data table of relevant data specifying the view fields and list type:


public DataTable getTasks(SPWeb web)
{

try
{

//creates the query

SPSiteDataQuery query = new SPSiteDataQuery();


//builds the query

query.Query = "< Where >" +

"< And >" +

"< Eq >" +

"< FieldRef Name='AssignedTo' LookupId='TRUE'/ >" +

"< Value Type='int' >< UserID / >< /Value >" +

"< /Eq >" +

"< Neq >" +

"< FieldRef Name='Status' / >" +

"< Value Type='Choice' >Completed< /Value >" +

"< /Neq >" +

"< /And >" +

"< /Where >";

//Sets the list types to search

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


//Sets the Fields to include in results

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

"< FieldRef Name='Status' / >";



//sets the scope of the query

query.Webs = "< Webs Scope='Recursive' / >";



//searches based on the query

DataTable table = web.GetSiteData(query);

//returns results

return table;

}

catch (Exception ex)
{

Response.Write("The following error occured while retrieving tasks: " + ex.Message + "< br / >");

}

//returns a blank datatable if error

return new DataTable();



}

This is a simple cross list query that returns all uncompleted tasks assigned to the current user based on all Tasks Lists in the current Site Collection. I haven't discussed CAML in detail but this is something I promise to post on in the near future. Any Hoo, this is one trick that I definitely pull out of the bag often.

~:)

3 comments:

P.O. said...

Thanks for this. Saved me a lot of time. I had to remove all the spaces in the query for it to work. Maybe because I'm using it in a web part? Thanks again!

omenof said...

Have you had any success in using the crosslist query to "JOIN" two diferent types of list such as blog post list and pages library. I am attempting to do this and it seems that one source will always override the other but never at the same time.

Anonymous said...

sherron transgenic centurylike hormones piecemeal ensa broader populate punish gateshead kipling
servimundos melifermuly