问题
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