1

我想在以下查询中获取朋友列表,但我得到了一个无限循环,这是我的示例数据:

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)
4

2 回答 2

1

(更新)一种方式:

;WITH cte AS
(SELECT convert(nvarchar(max),';'+name+';') namelist, t.Name, t.friends 
 FROM @t t WHERE name = 'Joe'
 UNION ALL
 SELECT convert(nvarchar(max),c.namelist+c.Friends+';'), 
        c.Friends, 
        case c.friends when t.name then t.friends else t.name end
 FROM cte c
 JOIN @t t 
   ON c.friends IN (t.name, t.friends) AND
      charindex(';'+case c.friends when t.name then t.friends else t.name end+';', 
                c.namelist)=0
)
SELECT name FROM cte UNION SELECT friends FROM cte
OPTION (maxrecursion 0)

SQLFiddle在这里

于 2013-11-02T16:18:06.220 回答
0
declare @T table (Name nvarchar(50), Friends nvarchar(50))
insert into @T values 
('Joe','Jean'),
('Mike','Jean'),
('Jean','Zaki'),
('Zaki','Ali'),
('Mimi','Nana'),
('Chico','Yari'),
('Joe','Yari'),
('Mimi','Jean'),
('Mimi','Zaki'),
('Chico','Jean')

SELECT DISTINCT Name , STUFF(Flist, 1, 2, '') AS FriendsList
FROM @T t CROSS APPLY (
                       SELECT ', ' + Friends [text()]
                       FROM @T t2
                       WHERE t2.name = t.name
                       FOR XML PATH('')
                      )L(Flist)

这会给你这样的每个名字的所有朋友的列表..

结果集

Name    FriendsList
Chico   Yari, Jean
Jean    Zaki
Joe     Jean, Yari
Mike    Jean
Mimi    Nana, Jean, Zaki
Zaki    Ali
于 2013-11-02T16:07:27.967 回答