使用FOR XML PATH的XML顺序

时间:2016-11-22 16:28:18

标签: sql-server xml tsql

我写了一个XML查询,它以我想要的格式不同的格式创建订单:

select
    'sample' "@ponumber",
    'xxxxxx' "@cust",
    'yyyyyy' "@shipto",
    '999999'  "line/material",
    '20'      "line/qty",
    '777777'  "line/material",
    '20'      "line/qty"
for 
    xml path('root')

我得到以下输出:

<root ponumber="sample" cust="xxxxxx" shipto="yyyyyy">
  <line>
    <material>999999</material>
    <qty>20</qty>
     <material>777777</material>
    <qty>20</qty>
  </line>
</root>

所需的输出是:

<root ponumber="sample" cust="xxxxxx" shipto="yyyyyy">
  <line>
    <material>999999</material>
    <qty>20</qty>
  </line>
  <line>
    <material>777777</material>
    <qty>20</qty>
  </line>
</root>

我的查询需要修改什么?

谢谢!

1 个答案:

答案 0 :(得分:5)

这将为您提供所需的输出。它的工作方式在Stack Overflow上解释here

select
    'sample' "@ponumber",
    'xxxxxx' "@cust",
    'yyyyyy' "@shipto",
    '999999'  "line/material",
    '20'      "line/qty",
    '',
    '777777'  "line/material",
    '20'      "line/qty"
for 
    xml path('root')

可生产

<root ponumber="sample" cust="xxxxxx" shipto="yyyyyy">
  <line>
    <material>999999</material>
    <qty>20</qty>
  </line>
  <line>
    <material>777777</material>
    <qty>20</qty>
  </line>
</root>