-
Erland Sommarskog 78,826 Reputation points MVP
2021-09-13T21:21:10.33+00:00 It's not clear to me what result you want, but to avoid the infinite recursion with the reciprocal dependencies, you need to use a materialised path to avoid re-visiting relations. Maybe this can be a start:
WITH sib ( RelationID, person, Sibling, ReciprocalRelationID, path ) AS ( SELECT r.RelationID, r.Person, r.Sibling, r.ReciprocalRelationID, cast(cast(r.RelationID AS char(10)) as varchar(MAX)) FROM @RELATIONSHIP r WHERE r.Person = @person UNION ALL SELECT r2.RelationID, r2.Person, r2.Sibling, r2.ReciprocalRelationID, path + cast(r2.RelationID AS char(10)) FROM sib s JOIN @RELATIONSHIP AS r2 ON r2.Person = s.Sibling WHERE charindex(cast(r2.RelationID AS char(10)), s.path) = 0 AND charindex(cast(r2.ReciprocalRelationID AS char(10)), s.path) = 0 ) SELECT * FROM sib
`
Your data has a circular dependency.
RelationId = 1 has a ReciprocalRelationID = 3
RelationId = 3 has a ReciprocalRelationID = 1