sql导出到xml的值与one相同

时间:2017-05-12 10:04:53

标签: sql sql-server xml export

我有一张名为"位置"像这样:

{
  "took" : 1678,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 1,
    "max_score" : 0.0,
    "hits" : [ ]
  }
}

我不会将该表格导出为xml格式:

society  site  floor  room
---------------------------
 Apple  London first  office
 Apple  London first  Meeting
 Apple  London first  Conference
 Apple  London second  IT
 Apple  London second  HR
 Apple  Rome   second  CCM
 Apple  Rome   second  BM

我正在使用sql 2008.你能帮我吗?谢谢你。

2 个答案:

答案 0 :(得分:0)

在sql server中运行

SELECT * from Location FOR XML AUTO

答案 1 :(得分:0)

尝试这样(我添加了一个社会来展示所有级别的1:n结构:

DECLARE @mockup TABLE(society VARCHAR(100),[site] VARCHAR(100),[floor] VARCHAR(100),room VARCHAR(100));
INSERT INTO @mockup VALUES
 ('Apple','London','first','office')
,('Apple','London','first ','Meeting')
,('Apple','London','first','Conference')
,('Apple','London','second','IT')
,('Apple','London','second','HR')
,('Apple','Rome','second','CCM')
,('Apple','Rome','second','BMD')
,('Orange','Vienna','first','Test');

SELECT m1.society AS [@name]
      ,(
        SELECT m2.[site] AS [@name]
              ,(
                SELECT m3.[floor] AS [@name]
                      ,(
                        SELECT m4.room
                        FROM @mockup AS m4
                        WHERE m4.society=m1.society AND m4.[site]=m2.[site] AND m4.[floor]=m3.[floor] 
                        GROUP BY m4.room
                        FOR XML PATH(''),TYPE
                       )
                FROM @mockup AS m3
                WHERE m3.society=m1.society AND m3.[site]=m2.[site] 
                GROUP BY m3.[floor]
                FOR XML PATH('floor'),TYPE
               )
        FROM @mockup AS m2
        WHERE m2.society=m1.society
        GROUP BY m2.[site]
        FOR XML PATH('site'),TYPE
       )
FROM @mockup AS m1
GROUP BY m1.society
FOR XML PATH('Society'),ROOT('LocationData');

结果

<LocationData>
  <Society name="Apple">
    <site name="London">
      <floor name="first">
        <room>Conference</room>
        <room>Meeting</room>
        <room>office</room>
      </floor>
      <floor name="second">
        <room>HR</room>
        <room>IT</room>
      </floor>
    </site>
    <site name="Rome">
      <floor name="second">
        <room>BMD</room>
        <room>CCM</room>
      </floor>
    </site>
  </Society>
  <Society name="Orange">
    <site name="Vienna">
      <floor name="first">
        <room>Test</room>
      </floor>
    </site>
  </Society>
</LocationData>