1

我有以下格式的数据:

   user          Id         Value
   -------------------------------
   a             50000        5              
   a             50000        6   
   a             50000        7   
   b             50001        8   
   b             50001        9   
   b             50001        10

我想获得以下格式的格式化 XML

 <RootNode> 
     <User "a"> 
       <UserAttribute Id="50000" value="5"/>
       <UserAttribute Id="50000" value="6"/> 
       <UserAttribute Id="50000" value="7"/> 
     </User> 
     <User "b">
       <UserAttribute Id="50001" value="8"/> 
       <UserAttribute Id="50001" value="9"/> 
       <UserAttribute Id="50001" value="10"/> 
     </User>
 </RootNode>

我尝试了以下选择查询:

select 
   [user] as '@user', 
   [id] as 'UserAttribute/@id',
   [value] as 'UserAttribute/@value' 
from 
   dbo.test 
for xml path('User')

但它没有提供所需的输出。有人可以让我知道我错过了什么吗?

当前输出:

<User user="a">
  <UserAttribute id="50000" value="5" />
</User>
<User user="a">
  <UserAttribute id="50000" value="6" />
</User>
<User user="a">
  <UserAttribute id="50000" value="7" />
</User>
<User user="b">
  <UserAttribute id="50001" value="8" />
</User>
<User user="b">
  <UserAttribute id="50001" value="8" />
</User>
<User user="b">
  <UserAttribute id="50001" value="8" />
</User>
4

1 回答 1

0

测试数据

DECLARE @TABLE TABLE ([user] CHAR(1),Id INT, Value INT)
INSERT INTO @TABLE VALUES
('a',50000,5),              
('a',50000,6),   
('a',50000,7),   
('b',50001,8),   
('b',50001,9),   
('b',50001,10)

询问

SELECT t.[user]        AS [@User]
       ,(SELECT Id     AS [@Id]
                ,Value AS [@Value]
         FROM @TABLE 
         WHERE [user] = t.[user]
         FOR XML PATH('UserAttribute'), TYPE)
FROM @TABLE t
GROUP BY t.[user]
FOR XML PATH('User'), ROOT('RootNode')

结果:

<RootNode>
  <User User="a">
    <UserAttribute Id="50000" Value="5" />
    <UserAttribute Id="50000" Value="6" />
    <UserAttribute Id="50000" Value="7" />
  </User>
  <User User="b">
    <UserAttribute Id="50001" Value="8" />
    <UserAttribute Id="50001" Value="9" />
    <UserAttribute Id="50001" Value="10" />
  </User>
</RootNode>

笔记

用户标签必须将 [User] 值作为属性,您不能像在所需输出中显示的那样向标签添加字符。<User "a">这不是 XML 的有效格式,您需要 [User] 值作为属性,如我的输出所示<User User="a">

于 2014-05-10T01:24:17.823 回答