1

我已经使用对问题Hierarchical data in Linq - options and performance的公认答案成功地查询了特定记录/节点的所有后代的层次表。现在我需要找到特定节点是其后代的树的根。我怎样才能使用尽可能接近的解决方案作为接受的答案来做到这一点?

层次结构由具有 ParentId 列的自引用表表示,该列对于层次结构中的顶部项目为空。

4

1 回答 1

0

这是你要找的东西吗

CREATE TABLE [dbo].[hierarchical_table](
    [id] INT,
    [parent_id] INT,
    [data] VARCHAR(255)
)
GO

INSERT [dbo].[hierarchical_table]
SELECT 1,NULL,'/1' UNION ALL
SELECT 2,1,'/1/2' UNION ALL
SELECT 3,2,'/1/2/3' UNION ALL
SELECT 4,2,'/1/2/4' UNION ALL
SELECT 5,NULL, '/5' UNION ALL
SELECT 6,5,'/5/6'
GO

CREATE FUNCTION [dbo].[fn_root_for_node] 
(
    @id int
)
RETURNS TABLE AS
RETURN (
    WITH [hierarchy_cte](id, parent_id, data, [Level]) AS
    (
        SELECT
            id,
            parent_id,
            data,
            0 AS [Level]
        FROM dbo.hierarchical_table
        WHERE id = @id
        UNION ALL
        SELECT t1.id, t1.parent_id, t1.data, h.[Level] + 1 AS [Level]
        FROM  dbo.hierarchical_table AS t1
        INNER JOIN hierarchy_cte AS h
            ON t1.id = h.parent_id
    )
    SELECT TOP 1
        id, parent_id, data, [Level]
    FROM [hierarchy_cte]
    ORDER BY [Level] DESC
)
GO

SELECT * FROM [dbo].[fn_root_for_node] (6)
GO
于 2012-12-02T16:22:16.683 回答