在SQL中将行转换为XML节点

时间:2016-07-25 10:05:58

标签: sql sql-server xml tsql

我必须从两个列表中返回XML,如下面的格式

TABLE

month       count
-----       ----
January     578
February    300
March       147
April       45
May         8

XML

<January>578</January>
<February>300</February>
<March>147</March>
<April>45</April>
<May>8</May>

我尝试过以下SQL语句,

SELECT * FROM #temp;

SELECT (
   SELECT monthId AS 'month/@atr', count AS month
   FROM #temp
   FOR XML PATH(''), TYPE
) 
FOR XML PATH('')

我知道上面的脚本用于获取第一列值作为属性。 在我的例子中,我需要第一列值作为节点,第二列作为其值。

感谢您的帮助。

3 个答案:

答案 0 :(得分:4)

DECLARE @t TABLE ([month] VARCHAR(50) PRIMARY KEY, [count] INT)

INSERT INTO @t
VALUES
    ('January', 578), ('February', 300),
    ('March', 147), ('April', 45), ('May', 8)

SELECT *
FROM @t
PIVOT (
    SUM(count)
    FOR month IN ([January], [February], [March], [April], [May], [June], [Jule]) 
) p
FOR XML PATH('')

答案 1 :(得分:4)

在直接的方式上,您可以(可能)使用pivot或使用动态SQL:

DECLARE @tbl TABLE([month] VARCHAR(100),[count] INT);
INSERT INTO @tbl VALUES
 ('January',578)
,('February',300)
,('March',147)
,('April',45)
,('May',8);

DECLARE @cmd VARCHAR(MAX)=
'SELECT ' +
(
    STUFF(
    (
        SELECT ',' + CAST(tbl.[count] AS VARCHAR(100)) + ' AS [' + tbl.[month] + ']'
        FROM @tbl AS tbl
        FOR XML PATH('')
    ),1,1,''
    ) 
)
+
' FOR XML PATH('''');';

EXEC(@cmd);

结果

<January>578</January>
<February>300</February>
<March>147</March>
<April>45</April>
<May>8</May>

但我不会这样做......

更好(更容易查询!)来创建这样的结构:

SELECT tbl.[month] AS [@name]
      ,tbl.[count] AS [*]
FROM @tbl AS tbl
FOR XML PATH('month');

结果

<month name="January">578</month>
<month name="February">300</month>
<month name="March">147</month>
<month name="April">45</month>
<month name="May">8</month>

答案 2 :(得分:4)

奇怪,但服务于目的,

DECLARE @MyTable TABLE ( Month VARCHAR(20), Count INT)

INSERT INTO @MyTable (Month, Count) 
VALUES 
     ('January' , 578)
    ,('February', 300)
    ,('March'   , 147)
    ,('April'   , 45 )
    ,('May'     , 8  )

SELECT 
  CAST('<' + Month + '>' + CAST(Count AS VARCHAR(20)) + '</' + Month + '>' AS XML) 
FROM @MyTable
FOR XML PATH('')

----输出----

<January>578</January>
<February>300</February>
<March>147</March>
<April>45</April>
<May>8</May>