Convert SQL table to XML with 2 node for each row

∥☆過路亽.° 提交于 2019-12-10 23:12:29

问题


My MS SQL table has following data

    ID    CONTENT     FLAG       TEXT
    ----------------------------------
    1     content1    T          text1
    2     content2    F          text2
    3     content3    T          text2

and i want to select values from this table in below format without any root node.

<ADDRESS ID="1" FLAG="T">
<FORM CONTENT="content1" TEXT="text1"/>
</ADDRESS>

<ADDRESS ID="2" FLAG="F">
<FORM CONTENT="content2" TEXT="text2"/>
</ADDRESS>

<ADDRESS ID="3" FLAG="T">
<FORM CONTENT="content3" TEXT="text3"/>
</ADDRESS>

回答1:


This is quite a while ago, but - just in case you're still interested in a solution - this would be the query:

 DECLARE @tbl TABLE(ID INT,CONTENT VARCHAR(100),FLAG VARCHAR(1),TEXT VARCHAR(100));
 INSERT INTO @tbl VALUES
 (1,'content1','T','text1')
,(2,'content2','F','text2')
,(3,'content3','T','text2');

SELECT tbl.ID AS [@ID]
      ,tbl.FLAG AS [@FLAG]
      ,tbl.CONTENT AS [Form/@CONTENT]
      ,tbl.TEXT AS [Form/@Text]
FROM @tbl AS tbl
FOR XML PATH('ADDRESS') /*,ROOT('Root')*/ --add Root if you need it

The Result

<ADDRESS ID="1" FLAG="T">
  <Form CONTENT="content1" Text="text1" />
</ADDRESS>
<ADDRESS ID="2" FLAG="F">
  <Form CONTENT="content2" Text="text2" />
</ADDRESS>
<ADDRESS ID="3" FLAG="T">
  <Form CONTENT="content3" Text="text2" />
</ADDRESS>


来源:https://stackoverflow.com/questions/33149049/convert-sql-table-to-xml-with-2-node-for-each-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!