SqlServer使用公用表表达式(CTE)实现无限级树形构建

(编辑:jimmy 日期: 2024/12/28 浏览:2)

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);
        }
      }
    }

一句话新闻

微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。