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

时间:2015-01-08 07:10:33

标签: sql-server sql-server-2008 for-xml-path

我有以下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份文件?

1 个答案:

答案 0 :(得分: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')