收录日期:2019/04/20 16:46:26 时间:2010-06-22 20:20:18 标签:sql,sql-server,xml

I want the following query to return the fields in a parent child format. Is this possible?

Here's the query

SELECT   Field1,
         Field2,
         Field3
FROM     ATable
GROUP BY Field1,
         Field2,
         Field3
ORDER BY Field1,
         Field2,
         Field3 
FOR xml auto

Here's what I would like to get back (doesn't have to be exaxtly like this, I just need the hierarchy.) I cant seem to get the rest of the xml displayed but this is most of it.

<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/>   

You could use the type option to nest XML queries. Here's an example:

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

-->

<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>

This does tend to get complicated, so instead of generating XML using SQL, consider a client side language like C# or VB.NET instead.