As per request by some of my readers who wanted information about how you can query SharePoint lists using joins in SharePoint 2010, here’s an introduction!
With the introduction of relational lists in SharePoint 2010, they also introduced a new set of investments in how we can interact with our lists.
We now have Projected fields, joins and relational integrity between parent and child lists.
Projected Fields & Relational Integrity will be covered in an upcoming blog series.
With our new relational lists in SharePoint 2010, we also have a better support for joins. Generally there’s the following ways of joining lists to pull out aggregated data:
- SharePoint API (SPQuery object)
- LINQ to SharePoint
- SharePoint Designer 2010
In this article I will touch upon the SPQuery enhancements regarding joins and relational data, and will cover the rest in future articles.
Using the object model with SharePoint 2010, you now have the ability to use some new fancy properties of the SPQuery object:
With the new property called Joins on the SPQuery object, we can (using CAML, as usual..) define a join for our query like so:
<Join Type=’LEFT ListAlias=’List1‘>
<FieldRef Name=’Field1′ RefType=’Id’ />
<FieldRef Name=’ID’ List=’List1‘ />
<Join Type=’LEFT’ ListAlias=’List2‘>
<FieldRef List=’List1‘ Name=’SomeFieldName’ RefType=’Id’ />
<FieldRef List=’List2‘ Name=’ID’ />
A working sample of the SPQuery code could look like this:
SPQuery query = new SPQuery();
query.Query = "[YOUR CAML QUERY HERE]";
query.Joins = "[YOUR JOIN CAML HERE (See above for example)]";
query.ViewFields = "[SAME AS BEFORE]";
SPListItemCollection items = myList.GetItems(query);
foreach(SPListItem item in items)
// Work with your items here like you’re used to, but now all joined up!
So the only thing you really need to do is to make sure you’ve got the join set up with the SPQuery.Joins property – and then shoot!
The SDK states the ProjectedFields property quite clearly:
You should have a go at this link to learn more about projected fields, and how you can utilize them in your SPQuery objects:
It’s pretty easy to do joins using the SPQuery object in the SharePoint object model these days, and all you really need to do is have a quick look at the SPQuery class in order to grasp the news.
So, pretty easy huh?
– Well, even more easy is to use LINQ to SharePoint, which I will try to cover in an article later this week.
Latest posts by Tobias Zimmergren (see all)
- Dev tip: Use Requestbin for easy analysis and debugging when developing your webhooks, connectors, API’s and applications - January 4, 2016
- Creating an ASP.NET 5 site with Visual Studio Code – Part 3: Adding npm packages and automating tasks with Gulp (adding Office UI Fabric) - October 4, 2015
- Creating an ASP.NET 5 site with Visual Studio Code – Part 2: Create your Visual Studio Code project using Yeoman - October 1, 2015