SqlServer中怎么利用公用表表達(dá)式實(shí)現(xiàn)無(wú)限級(jí)樹(shù)形構(gòu)建,針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。
在杏花嶺等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強(qiáng)發(fā)展的系統(tǒng)性、市場(chǎng)前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務(wù)理念,為客戶提供做網(wǎng)站、網(wǎng)站制作 網(wǎng)站設(shè)計(jì)制作按需網(wǎng)站開(kāi)發(fā),公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),品牌網(wǎng)站設(shè)計(jì),營(yíng)銷型網(wǎng)站,成都外貿(mào)網(wǎng)站建設(shè)公司,杏花嶺網(wǎng)站建設(shè)費(fèi)用合理。SQL Server 2005開(kāi)始,我們可以直接通過(guò)CTE來(lái)支持遞歸查詢,CTE即公用表表達(dá)式
公用表表達(dá)式(CTE),是一個(gè)在查詢中定義的臨時(shí)命名結(jié)果集將在from子句中使用它。每個(gè)CTE僅被定義一次(但在其作用域內(nèi)可以被引用任意次),并且在該查詢生存期間將一直生存。可以使用CTE來(lái)執(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 ListGetLogisticsCategoryByParent(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 allCategoryList, List 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 (); category.children.AddRange(subCategoryList); BuildCategory(allCategoryList, category.children); } } }
關(guān)于SqlServer中怎么利用公用表表達(dá)式實(shí)現(xiàn)無(wú)限級(jí)樹(shù)形構(gòu)建問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識(shí)。