select for xml,按字段顺序嵌套

时间:2010-02-12 13:20:01

标签: xml tsql

SELECT 
      [Represantative] 
      ,[log_date] 
      ,[customer] 
      ,[type] 
      ,[log_type] 
      ,[zone_code] 
  FROM [dbo].[ilc_ziyaret_plani_gun_degisiklikleri_v] gun_logu
order by Represantative, log_date, customer
for xml path ,  root('log_details')

我需要在order by子句中嵌套的xml:我尝试使用for xml path子句,但它没有进行嵌套,它只是塑造了xml doc。 Represantative,log_date,customer

<log_details>
 <represantative name="john doe">
  <log_date date="2010-02-10">
   <customer c="xyz">
    <op>
      <log_type="add"/>
      <zone_code="a1"/>
    </op>
    <op>
      <log_type="add"/>
      <zone_code="b1"/>
    </op>
   <customer/>
   <customer> same as above </customer>
  <log_date>same for next date</log_date>

任何想法如何做到这一点

1 个答案:

答案 0 :(得分:0)

在TSQL中格式化xml需要一些试验和错误

SELECT  
      [Represantative] 
      ,[log_date]  
      ,[customer]  "customer/@name"
      ,[type]  "customer/@type"
      ,[log_type] "customer/op/log_type" 
      ,[zone_code]  "customer/op/zone_code"
  from t1
order by Represantative, log_date, customer 
for xml path('log_detail') ,  root('log_details') 

返回此xml输出

<log_details>
  <log_detail>
    <Represantative>john doe</Represantative>
    <log_date>2010-02-10</log_date>
    <customer name="xyz" type="add">
      <op>
        <log_type>a1</log_type>
        <zone_code>b1</zone_code>
      </op>
    </customer>
  </log_detail>
</log_details>