这个小城,步入冬天就立马变了颜色,还没来得及等我换件衣服就开演了。如何扮演好自己的角色,我还没想好,我不适合做主角,只能在配角方面下功夫,极力配合主角旦,生的表演。红红火火的演完这场戏,让北方的冬天刮目相看。
SQL Server 2005开始,我们可以直接通过CTE来支持递归查询,CTE即公用表表达式
公用表表达式(CTE),是一个在查询中定义的临时命名结果集将在from子句中使用它。每个CTE仅被定义一次(但在其作用域内可以被引用任意次),并且在该查询生存期间将一直生存。可以使用CTE来执行递归操作。
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, Level FROM 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); } } }
到此这篇关于SqlServer如何使用公用表表达式(CTE)如何实现无限级树形构建就介绍到这了。只有把握现在,才能在明天驰骋风云,只有把握现在,才能充实虚幻的明天,只有把握现在,才能造就明天的辉煌!更多相关SqlServer如何使用公用表表达式(CTE)如何实现无限级树形构建内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!