1

我有一个简单的SELECT语句,它从单个表中选择几列:

SELECT id, name, phone, address 
FROM tmp_user

是否可以更改此查询,以便仅idname在 select 中,其余详细信息在 xml 节点中?

我预计这个选择的输出应该是

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>

返回表的最后一列应该是带有所需数据的 XML 类型。我知道如何使用 FOR XML 将整个结果集转换为 XML。但是,我只寻找要转换的部分列。可能吗?

4

1 回答 1

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.

enter image description here

于 2012-04-28T11:29:12.937 回答