使用特定的XSD定义从Query生成XML?

时间:2014-12-05 18:25:21

标签: sql-server xml sql-server-2005 xquery

我有以下查询

select A,B,C,D,E,F,G,H from View1 where A = '....'

我想生成以下XML。是否可以使用Sql Server for XML来执行此操作?或者有没有其他方法可以在SQL服务器中实现?

<Root>
  <A>....</A> <!-- Appear only once -->
  <B Id="1">
    <Type C="..." D="...">
      <SubType>
        <Element E="..." F="....">
          <G>...</G>
          <H>...</H>
        </Element>
        .....
      </Subtype>
      ....
    <Type>
    .....
  </B>
  <B>.....

1 个答案:

答案 0 :(得分:2)

FOR XML PATH可用于获得所需的结果

declare @test table
(
 A int,
 B int,
 C int,
 D int,
 E int,
 F int,
 G int
)

insert into @test values (1,2,3,4,5,6,7)
insert into @test values (1,3,4,4,5,6,7)

SELECT 
(SELECT top 1 A from @test WHERE A=1 ) as 'A/text()',
( 
      SELECT        
       B as '@id',
       (SELECT C as '@C', D as '@D', 
                E as 'SubType/Element/@E', F as 'SubType/Element/@F',
                G as 'SubType/Element/G/text()',
                F as 'SubType/Element/F/text()' 
         FOR XML PATH('Type'), TYPE
        )
       FROM @test
       WHERE A =1
       FOR XML PATH('B'), TYPE
)
FOR XML PATH(''), ROOT('ROOT')