Answer the question
In order to leave comments, you need to log in
How to filter a tree?
There is a table:
declare @tree table
(
id int,
ParentID int,
Name varchar(100)
);
insert @tree values
(1,null,'111'),
(2,1,'222'),
(3,1,'333'),
(4,2,'444'),
(5,2,'555'),
(6,4,'666'),
(7,4,'777');
Answer the question
In order to leave comments, you need to log in
How can it be filtered by Name so that if the found row had parents by ParentID and he pulled them all out?
SELECT * FROM @tree AS a WHERE a.Name LIKE '%444%'
UNION
SELECT b.* FROM @tree AS a
INNER JOIN @tree AS b ON b.id = a.ParentID
WHERE a.Name LIKE '%444%'
;WITH hierarchy
(
[level], id, ParentID, Name
)
AS
(
SELECT
0, id, ParentID, Name
FROM @tree AS a
WHERE a.name LIKE '%444%'
UNION ALL
SELECT
h.[level] + 1, b.id, b.ParentID, b.Name
FROM @tree AS b
INNER JOIN hierarchy AS h ON h.ParentID = b.id
)
SELECT * FROM hierarchy;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question