在一列上获取子记录

Die*_*ego 3 sql sql-server sql-server-2005

我有一个表父和一个表子,像这样:

Parent
ID   Name
1    Parent1
2    Parent2

Son
ID   ParentID
10      1
20      1
30      1
15      2
25      2
Run Code Online (Sandbox Code Playgroud)

选择父母时,最简单的方法是在同一列上获得儿子的所有ID?像这样:

Result:
ID   Name      AllMySons
1    Parent1   10,20,30
2    Parent2   15, 25
Run Code Online (Sandbox Code Playgroud)

我想到建立一个函数来生成带有儿子的字符串,但是有人有更好的主意吗?

Mik*_*son 5

select P.ID,
       P.Name,
       stuff((select ','+cast(S.ID as varchar(10))
              from Son S
              where S.ParentID = P.ID
              for xml path('')), 1, 1, '') AllMySons
from Parent P
Run Code Online (Sandbox Code Playgroud)

SE数据