在SharePoint平台二次开发中,我们有时需要涉及多表关联查询展示多列表中的不同字段信息;SharePoint和Sql数据表一样,也支持多表联合查询,但是不像Sql语句那样简单,有一定的局限性,需要使用SPQuery的Joins属性来完成。
联合查询的前提条件:
1、子列表必须采用查阅项进行关联主表;
下面,我们通过一个简单的例子,为大家演示一下如何使用SPQuery通过查阅项字段来进行两个列表的联合查询。
1、创建主列表,City是城市;子列Address,是地址,子列表新增加查阅项CityLook进行关联,如下表所示:
2、执行查询语句:
1 string SiteUrl = Microsoft.SharePoint.SPContext.Current.Site.Url ; 2 using (SPSite site = new SPSite(SiteUrl)) 3 { 4 using (SPWeb web = site.OpenWeb("/Test")) 5 { 6 SPQuery query = new SPQuery(); 7 //Joins属性,这里有INNER和LEFT两种方式连接,均可查询,而且支持多表连接; 8 query.Joins = "<Join Type='INNER' ListAlias='City'>" + 9 "<Eq>" + 10 "<FieldRef Name='CityLook' RefType='ID'/>" + 11 "<FieldRef List='City' Name='ID'/>" + 12 "</Eq>" + 13 "</Join>"; 14 15 16 //设置关联的查阅项字段 17 query.ProjectedFields = "<Field Name='CityDescription' Type='Lookup' List='City' ShowField='Description'/>" + 18 "<Field Name='CityCode1' Type='Lookup' List='City' ShowField='Code'/>"; 19 //设置需要显示的字段 20 query.ViewFields = "<FieldRef Name='ID'/>" + 21 "<FieldRef Name='Title'/>" + 22 "<FieldRef Name='CityCode'/>" + 23 "<FieldRef Name='CityLook'/>" + 24 "<FieldRef Name='CityCode1'/>" + 25 "<FieldRef Name='CityDescription'/>"; 26 27 //query.Query = "<Where><Eq><FieldRef Name='CityCode'/><Value Type='Text'>XM</Value></Eq></Where>"; 28 //查阅项查询,采用ID值进行查询 29 query.Query = "<Where><Eq><FieldRef Name='CityLook' LookupId='TRUE'/><Value Type='Lookup'>4</Value></Eq></Where>"; 30 31 SPList list = web.Lists["Address"]; 32 33 SPListItemCollection items = list.GetItems(query); 34 35 foreach (SPListItem item in items) 36 { 37 SPFieldLookupValue CityLook = new SPFieldLookupValue(item["CityLook"].ToString()); 38 SPFieldLookupValue CityCode1 = new SPFieldLookupValue(item["CityCode1"].ToString()); 39 40 string info = "ID:" + item.ID.ToString() +";"+ 41 "Title:" + item["Title"].ToString() + ";" + 42 "CityCode:" + item["CityCode"].ToString() + ";" + 43 "CityDescription:" + item["CityDescription"].ToString() + ";" + 44 "CityCode1:" + CityCode1.LookupValue + "[" + CityCode1.LookupId + "]" + ";" + 45 "CityLook:" + CityLook.LookupValue + "[" + CityLook.LookupId + "]"; 46 Response.Write(info + "<br />"); 47 } 48 49 //DataTable dtData = items.GetDataTable(); 50 //GridView1.DataSource = dtData; 51 //GridView1.DataBind(); 52 } 53 }
3、执行效果图:
注意事项:
1、Join属性类型Type若设置为LEFT时,若主表字段删除后,则加载可能会出错;
2、主表的字段若要在查询结果中体现,则需通过SPQuery.ProjectedFields设置查阅项的模式进行绑定显示;