Try this query, using different values of Groupname. If it works, then we'll pivot the results using FOR XML PATH to put them into a comma-delimited list:
;WITH rCTE AS (
SELECT Level = 1, Id, GroupId, GroupName, ParentGroupId, ParentGroupName
FROM dbo.groupsAssociation
WHERE [GroupName] IN ('A') --('A','C','D')
UNION ALL
SELECT Level = Level + 1, tr.Id, tr.GroupId, tr.GroupName, tr.ParentGroupId, tr.ParentGroupName
FROM dbo.groupsAssociation tr
INNER JOIN rCTE lr ON lr.GroupId = tr.ParentGroupId
WHERE lr.Level < 8
)
SELECT GroupId, GroupName, ParentGroupId, ParentGroupName
FROM rCTE
GROUP BY GroupId, GroupName
ORDER BY GroupName
For better assistance in answering your questions, please read this[/url].
Hidden RBAR: Triangular Joins[/url] / The "Numbers" or "Tally" Table: What it is and how it replaces a loop[/url] Jeff Moden[/url]