公用表表達(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,
Level
FROM cte_parent WHERE Level =@Level;
public static ListLogisticsCategoryTreeEntity> 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(ListLogisticsCategoryTreeEntity> allCategoryList, ListLogisticsCategoryTreeEntity> 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 ListLogisticsCategoryTreeEntity>();
category.children.AddRange(subCategoryList);
BuildCategory(allCategoryList, category.children);
}
}
}