如何在 SQL Server 上使用 FOR XML 创建层次结构

How to Create a hierarchy with FOR XML on SQLServer

我得到了以下 2 个包含数据的表格

declare @tab1 table(a int, name varchar(10), street varchar(20))
insert @tab1 values(1,'Bruce', 'my street')
insert @tab1 values(2,'Chuck', 'another street')

declare @tab2 table(a int, b varchar(10))
insert @tab2 values(1,'a')
insert @tab2 values(1,'b')
insert @tab2 values(2,'c')
insert @tab2 values(2,'e')

我正在尝试创建一个 XML 应该如下所示的文档

<Person>
    <PersonInfo>
        <Name>Bruce</Name>
        <Street>my street</Street>
    </PersonInfo>
    <PersonSkill>
        <Type>a</Type>
        <Type>b</Type>
    </PersonSkill>
</Person>

到目前为止我的 SQL 看起来像这样

SELECT name AS "PersonInfo/Name", 
street AS "PersonInfo/Street",
b AS "PersonSkill/Type"
FROM @tab1 t1 JOIN @tab2 t2 ON t1.a = t2.a
WHERE NAME = 'Bruce'
FOR XML PATH('Person') 

并给出这个结果

<Person>
    <PersonInfo>
        <Name>Bruce</Name>
        <Street>my street</Street>
    </PersonInfo>
    <PersonSkill>
        <Type>a</Type>
    </PersonSkill>
</Person>
<Person>
    <PersonInfo>
        <Name>Bruce</Name>
        <Street>my street</Street>
    </PersonInfo>
    <PersonSkill>
        <Type>b</Type>
    </PersonSkill>
</Person>

如何避免获得 2 个文档?

在列列表中针对 @tab2.

执行相关子查询
select T1.name as 'PersonInfo/Name',
       T1.street as 'PersonInfo/Street',
       (
       select T2.b as '*' 
       from @tab2 as T2
       where T2.a = T1.a
       for xml path('Type'), root('PersonSkill'), type
       ) 
from @tab1 as T1
where T1.name = 'Bruce'
for xml path('Person')