我希望以下查询以父子格式返回字段。这可能吗?
这是查询
SELECT Field1,
Field2,
Field3
FROM ATable
GROUP BY Field1,
Field2,
Field3
ORDER BY Field1,
Field2,
Field3
FOR xml auto
这就是我想要回来的东西(不一定非常像这样,我只需要层次结构。)我似乎无法显示其余的xml,但这是大部分内容。
<Field1 Value='1'>
<Field2 Value='1'>
<Field3 Value='2'>
</Field2>
<Field2 Value='2'/>
<Field2 Value='3'/>
<Field1/>
<Field1 Value='2'>
<Field2 Value='1'>
<Field3 Value='2'>
</Field2>
<Field2 Value='2'/>
<Field2 Value='3'/>
<Field1/>
答案 0 :(得分:2)
您可以使用type
选项嵌套XML查询。这是一个例子:
declare @t table (Field1 int, Field2 int, Field3 int)
insert @t values (1,1,2), (1,2,null), (1, 3, null),
(2,1,2), (2,2,null), (2,3,null)
select Field1 as 'Field1/@Value'
, (
select Field2 as 'Field2/@Value'
, (
select Field3 as 'Field3/@Value'
from @t t3
where t3.Field1 = t2.Field1
and t3.Field2 = t2.Field2
and Field3 is not null
for xml path(''), type
) as 'Field2'
from @t t2
where t2.Field1 = t1.Field1
and Field2 is not null
for xml path(''), type
) as 'Field1'
from @t t1
group by
Field1
for xml path(''), type
- &GT;
<Field1 Value="1">
<Field2 Value="1">
<Field3 Value="2" />
</Field2>
<Field2 Value="2" />
<Field2 Value="3" />
</Field1>
<Field1 Value="2">
<Field2 Value="1">
<Field3 Value="2" />
</Field2>
<Field2 Value="2" />
<Field2 Value="3" />
</Field1>
这确实会变得复杂,因此不要使用SQL生成XML,而应考虑使用C#或VB.NET等客户端语言。