Commander une requête basée sur un champ pointant vers la même table

J'ai une table appelée "Phrase" qui a les champs suivants:

ID <--- OK NextID <--- FK To ID Text 

Donc, si j'avais les loggings suivants:

 *ID* *NextID* *Text* 1 12 The quick 3 40 jumps over 5 null lazy dog. 12 3 brown fox 40 5 the 

Si je sais que le début de la séquence est l'logging avec ID = 1, existe-t-il un moyen de order une requête basée sur la séquence de NextID. Comme avec l'exemple ci-dessus, le résultat attendu devrait être …

 The quick brown fox jumps over the lazy dog. 

Je suis à la search d'une déclaration T-SQL ou d'une manière ou d'une autre avec Linq. Merci d'avance!

essaye ça:

 declare @YourTable table (RowID int primary key, NextID int, TextValue varchar(50)) INSERT INTO @YourTable VALUES (1 , 12 ,'The quick') INSERT INTO @YourTable VALUES (3 , 40 ,'jumps over') INSERT INTO @YourTable VALUES (5 , null,'lazy dog.') INSERT INTO @YourTable VALUES (12, 3 ,'brown fox') INSERT INTO @YourTable VALUES (40, 5 ,'the') ;with cteview as ( SELECT * FROM @YourTable WHERE RowID=1 UNION ALL SELECT y.* FROM @YourTable y INNER JOIN cteview c ON y.RowID=c.NextID ) select * from cteview OPTION (MAXRECURSION 9999) --go beyond default 100 levels of recursion to 9999 levels 

SORTIE:

 RowID NextID TextValue ----------- ----------- -------------------------------------------------- 1 12 The quick 12 3 brown fox 3 40 jumps over 40 5 the 5 NULL lazy dog. (5 row(s) affected) 

Réponse LINQ:

 table.OrderBy(sentence => sentence.NextID); 

Edit: J'espère avoir répondu correctement cette fois-ci:

 class Sentence { public int Id; public int? NextId; public ssortingng Text; public Sentence(int id, int? nextId, ssortingng text) { this.Id = id; this.NextId = nextId; this.Text = text; } } var Sentences = new [] { new Sentence(1, 12, "This quick"), new Sentence(3, 40, "jumps over"), new Sentence(5, null, "lazy dog."), new Sentence(12, 3, "brown fox"), new Sentence(40, 5, "the"), }; Func<int?, ssortingng> GenerateSentence = null; GenerateSentence = (id) => id.HasValue? Sentences .Where(s => s.Id == id.Value) .Select(s => s.Text + " " + GenerateSentence(s.NextId)) .Single() : ssortingng.Empty; Console.WriteLine(GenerateSentence(1)); 

Si vous utilisez LINQ to SQL / Entities, la class Sentence générée doit avoir toutes les propriétés que vous avez mentionnées, ainsi qu'une reference d'entité à la phrase suivante (appelons-la NextSentence) à partir de la key étrangère.

Alors vous pouvez simplement faire:

 Sentence s = Sentences.First(); SsortingngBuilder sb = new SsortingngBuilder(); do { sb.Append(s.Text); s = s.NextSentence; } while (s != null); 

et sb.ToSsortingng() aura votre réponse.