这个怎么样?
表 =>
Id ParentId 名称
漂亮的简单表?
那么用一些漂亮的复杂的 pf SQL 来搭配怎么样?(我认为 CTE 摇滚)
public object FetchCategoryTree()
{
var sql = @"SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
WITH AreaTree (ID, Name, ParentID, OrgLevel, SortKey) AS
(
-- Create the anchor query. This establishes the starting
-- point
SELECT
a.ID,
cast('---- ' + a.Name as varchar(255)),
a.ParentID,
cast('----' as varchar(55)),
CAST(a.ID AS VARBINARY(900))
FROM dbo.Area a
WHERE a.ParentID is null
UNION ALL
-- Create the recursive query. This query will be executed
-- until it returns no more rows
SELECT
a.ID,
cast('----' + b.OrgLevel + ' ' + a.Name as varchar(255)),
a.ParentID,
cast(b.OrgLevel+ '----' as varchar(55)),
CAST(b.SortKey + CAST (a.ID AS BINARY(4)) AS VARBINARY(900))
FROM dbo.Area a
INNER JOIN AreaTree b ON a.ParentID = b.ID
)
SELECT * FROM AreaTree
ORDER BY SortKey";
return FetchObject(sql);
}
现在,这做了一些不太确定的 SQL 魔术。然而,用外行的话来说,它基本上将第一部分作为根查询。然后它返回表并通过连接使用第一部分的答案执行第二部分,并继续执行它仍然找不到更多匹配项,基本上是一个大循环。它也很快。
你会得到一堆带有排序键的行。通过排序键对查询进行排序后,您将得到如下答案:
---- parent 1
-------- child 1
-------- child 2
------------ child 2.1
---- parent 2
-------- etc
可能是您正在寻找的东西?