我想在以下查询中获取朋友列表,但我得到了一个无限循环,这是我的示例数据:
DECLARE @T TABLE (Name nvarchar(50), Friends nvarchar(50))
INSERT INTO @T VALUES
('Joe','Jean'),
('Mike','Jean'),
('Jean','Zaki'),
('Zaki','Ali'),
('Mimi','Nana'),
('Mimi','Jean'),
('Chico','Yari')
和查询本身:
;WITH cte AS
(SELECT name rootname, t.* FROM @t t WHERE name = 'Joe'
UNION ALL
SELECT c.rootname, t.*
FROM cte c
JOIN @t t ON c.friends IN (t.name, t.friends) AND
t.name NOT IN (c.rootname, c.name)
)
SELECT name FROM cte UNION SELECT friends FROM cte
OPTION (maxrecursion 0)