this will return the tree structure for parent 1
DECLARE @Table TABLE(
ID INT,
Val VARCHAR(MAX),
ParentID INT
)
INSERT INTO @Table (ID,Val,ParentID) SELECT 1, 'a', NULL
INSERT INTO @Table (ID,Val,ParentID) SELECT 2, 'b', 1
INSERT INTO @Table (ID,Val,ParentID) SELECT 3, 'c', 1
INSERT INTO @Table (ID,Val,ParentID) SELECT 4, 'd', 2
INSERT INTO @Table (ID,Val,ParentID) SELECT 5, 'e', 2
INSERT INTO @Table (ID,Val,ParentID) SELECT 6, 'f', 3
INSERT INTO @Table (ID,Val,ParentID) SELECT 7, 'g', 3
INSERT INTO @Table (ID,Val,ParentID) SELECT 8, 'h', 4
INSERT INTO @Table (ID,Val,ParentID) SELECT 9, 'i', 4
INSERT INTO @Table (ID,Val,ParentID) SELECT 10, 'j', 5
INSERT INTO @Table (ID,Val,ParentID) SELECT 11, 'k', 5
INSERT INTO @Table (ID,Val,ParentID) SELECT 12, 'l', 6
DECLARE @ParentID INT
SET @ParentID = 1
;WITH TreeSelect AS(
SELECT ID,
Val
FROM @Table
WHERE ParentID = @ParentID
UNION ALL
SELECT t.ID,
t.Val
FROM @Table t INNER JOIN
TreeSelect ts ON t.ParentID = ts.ID
)
SELECT *
FROM TreeSelect
OPTION (MAXRECURSION 0)