1

I have used the accepted answer to the question Hierarchical data in Linq - options and performance successfully to query a hierarchical table for all descendants of a particular record/node. Now I need to find the root of the tree that a particular node is a descendant of. How can I use as close a possible solution as that accepted answer to do this?

The hierarchy is represented by a self-referencing table with a ParentId column, which is null for the top item in the hierarchy.

Community
  • 1
  • 1
ProfK
  • 49,207
  • 121
  • 399
  • 775

1 Answers1

0

Is this the kind of thing you're looking for

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
Tom Hunter
  • 5,714
  • 10
  • 51
  • 76