Selecting few columns of a result set as XML

本小妞迷上赌 提交于 2019-12-11 07:29:40

问题


I have a simple SELECT statement which selects few columns from a single table:

SELECT id, name, phone, address 
FROM tmp_user

Is it possible to change this query so that only id and name are in select and remaining details are in a xml node?

I expected output of this select should be

id  name        extra data
1   Shreedhar   <data><phone>...</phone><address>...</address></data>
2   John Doe    <data><phone>...</phone><address>...</address></data>
3   Jane Doe    <data><phone>...</phone><address>...</address></data>

The last column is of the returned table should be of XML type with required data. I know how the entire result set can be converted to XML using FOR XML. However I am looking only for part of the columns to be converted. Is it possible?


回答1:


Sure! No problem - try something like this:

SELECT 
    id, name,
    (SELECT phone, address
     FROM dbo.tmp_user u2
     WHERE u2.id = u1.id
     FOR XML PATH('data')) AS 'ExtraData'
FROM    
   dbo.tmp_user u1

This gives me an output pretty exactly like the one you're looking for.



来源:https://stackoverflow.com/questions/10357203/selecting-few-columns-of-a-result-set-as-xml

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