Domanda

I want to get the list of friends in the following query, but I'm getting an infinite loop, Here's my sample data:

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

and the query itself:

;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)
È stato utile?

Soluzione

(Updated) One way:

;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 here.

Altri suggerimenti

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)

This will give you list of all the friends for each name like this ..

Result Set

Name    FriendsList
Chico   Yari, Jean
Jean    Zaki
Joe     Jean, Yari
Mike    Jean
Mimi    Nana, Jean, Zaki
Zaki    Ali
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top