您好,登錄后才能下訂單哦!
SqlServer中怎么利用公用表表達(dá)式實(shí)現(xiàn)無限級樹形構(gòu)建,針對這個(gè)問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡單易行的方法。
SQL Server 2005開始,我們可以直接通過CTE來支持遞歸查詢,CTE即公用表表達(dá)式
公用表表達(dá)式(CTE),是一個(gè)在查詢中定義的臨時(shí)命名結(jié)果集將在from子句中使用它。每個(gè)CTE僅被定義一次(但在其作用域內(nèi)可以被引用任意次),并且在該查詢生存期間將一直生存??梢允褂肅TE來執(zhí)行遞歸操作。
DECLARE @Level INT=3;WITH cte_parent(CategoryID,CategoryName,ParentCategoryID,Level)AS( SELECT category_id,category_name,parent_category_id,1 AS Level FROM TianShenLogistic.dbo.ProductCategory WITH(NOLOCK) WHERE category_id IN ( SELECT category_id FROM TianShenLogistic.dbo.ProductCategory WHERE parent_category_id=0 ) UNION ALL SELECT b.category_id,b.category_name,b.parent_category_id,a.Level+1 AS Level FROM TianShenLogistic.dbo.ProductCategory b INNER JOIN cte_parent a ON a.CategoryID = b.parent_category_id)SELECT CategoryID AS value, CategoryName as label, ParentCategoryID As parentId, LevelFROM cte_parent WHERE Level <=@Level;public static List<LogisticsCategoryTreeEntity> GetLogisticsCategoryByParent(int? level) { if (level < 1) return null; var dataResult = CategoryDA.GetLogisticsCategoryByParent(level); var firstlevel = dataResult.Where(d => d.level == 1).ToList(); BuildCategory(dataResult, firstlevel); return firstlevel; } private static void BuildCategory(List<LogisticsCategoryTreeEntity> allCategoryList, List<LogisticsCategoryTreeEntity> categoryList) { foreach (var category in categoryList) { var subCategoryList = allCategoryList.Where(c => c.parentId == category.value).ToList(); if (subCategoryList.Count > 0) { if (category.children == null) category.children = new List<LogisticsCategoryTreeEntity>(); category.children.AddRange(subCategoryList); BuildCategory(allCategoryList, category.children); } } }
關(guān)于SqlServer中怎么利用公用表表達(dá)式實(shí)現(xiàn)無限級樹形構(gòu)建問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。