在SharePoint平臺二次開發中,咱們有時須要涉及多表關聯查詢展現多列表中的不一樣字段信息;SharePoint和Sql數據表同樣,也支持多表聯合查詢,可是不像Sql語句那樣簡單,有必定的侷限性,須要使用SPQuery的Joins屬性來完成。web
聯合查詢的前提條件:spa
一、子列表必須採用查閱項進行關聯主表;code
下面,咱們經過一個簡單的例子,爲你們演示一下如何使用SPQuery經過查閱項字段來進行兩個列表的聯合查詢。blog
一、建立主列表,City是城市;子列Address,是地址,子列表新增長查閱項CityLook進行關聯,以下表所示:ip
二、執行查詢語句:開發
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 }
三、執行效果圖:string
注意事項:it
一、Join屬性類型Type若設置爲LEFT時,若主表字段刪除後,則加載可能會出錯;io
二、主表的字段若要在查詢結果中體現,則需經過SPQuery.ProjectedFields設置查閱項的模式進行綁定顯示;class