I rewrote your query to distinguish between individuals and groups. I did some simplification that may not be warranted. Specifically, I removed the cycle check, because you should not have cycles, but you can always add a depth check to stop processing after a certain depth.
;WITH Members AS
(
--Anchor
SELECT
GroupCode,
Member
FROM #GroupMembers
WHERE MemberType = 'Individual'
UNION ALL
--Recursive call
SELECT h.GroupCode, m.Member
FROM #GroupMembers h
INNER JOIN Members m
ON h.Member = m.GroupCode
WHERE h.MemberType = 'Group'
)
SELECT *
FROM Members m
WHERE @GroupCode = GroupCode
This gives me most of the results that you expect, and the one case where it is different (5), I think that your expected results are wrong.
Drew
J. Drew Allen
Business Intelligence Analyst
Philadelphia, PA