使用SQL Server嵌套FOR XML结果

时间:2015-10-19 09:28:39

标签: sql-server xml nested xmlroot

我的MS SQL表有以下数据

ObjectManager

并且我想以下面的格式从这个表中选择值而没有任何根节点。

ID    CONTENT     UDH         TO       FROM
-------------------------------------------
1     HELLO       1          9812      22
2     HELLO       1          9813      22
3     HELLO       1          9814      22

它是我之前发布的内容的清晰版本 here

1 个答案:

答案 0 :(得分:2)

尝试这样(根据你的评论):

    DECLARE @tbl TABLE(ID INT,CONTENT VARCHAR(100),UDH INT,[TO] INT,[FROM] INT);
INSERT INTO @tbl VALUES
 (1,'HELLO',1,9812,22)
,(2,'HELLO',1,9813,22)
,(3,'HELLO',1,9814,22);

SELECT tbl.CONTENT AS [@CONTENT]
      ,tbl.UDH AS [@UDH]
      ,tbl.[TO] AS [ADDRESS/@TO]
      ,tbl.[FROM] AS [ADDRESS/@FROM]
FROM @tbl AS tbl
FOR XML PATH('SMS')

/* Result
<SMS CONTENT="HELLO" UDH="1">
  <ADDRESS TO="9812" FROM="22" />
</SMS>
<SMS CONTENT="HELLO" UDH="1">
  <ADDRESS TO="9813" FROM="22" />
</SMS>
<SMS CONTENT="HELLO" UDH="1">
  <ADDRESS TO="9814" FROM="22" />
</SMS>
*/