对于XML Path - SQL Server

时间:2015-03-25 10:02:44

标签: sql-server xml

我在SQL Server表中有数据,如下所示。

**Name      Date        AA   BB  CC**
Customer1   3-Mar-15    234  56  4567
Customer2   4-Mar-15    55   66   77

现在我希望这些数据的格式如下所示。

<ReturnsList>
    <Return Label='AA' Days = 1 value = '234'></Return>
    <Return Label='BB' Days = 2 value = '56'></Return>
    <Return Label='CC' Days = 3 value = '4567'></Return>
</ReturnsList>
<ReturnsList>
    <Return Label='AA' Days = 1 value = '55'></Return>
    <Return Label='BB' Days = 2 value = '66'></Return>
    <Return Label='CC' Days = 3 value = '77'></Return>
</ReturnsList>

我尝试过不同的方式:

SELECT 

 (Select AA  AS "AA", 

   BB AS "BB",

   CC AS "CC"

from table
for xml path('Return') ,type
)
FOR XML PATH ('ReturnsList'); 

我没有按预期获得xml格式。

有人可以帮忙吗?

谢谢你, 米塔尔。

2 个答案:

答案 0 :(得分:1)

FOR XML PATH对行集进行操作。因此,您必须将单行数据转换为一组行。您可以使用UNPIVOT

SELECT Name, Labels, LabelValue, 
       CASE 
          WHEN Labels = 'AA' THEN 1
          WHEN Labels = 'BB' THEN 2
          WHEN Labels = 'CC' THEN 3
       END AS [Days]
FROM 
   (SELECT Name, AA, BB, CC
    FROM #mytable) p
UNPIVOT (
   LabelValue FOR Labels IN ([AA], [BB], [CC])
)AS unpvt

<强>输出:

    Name        Labels  LabelValue  Days
   --------------------------------------
    Customer1   AA      234         1
    Customer1   BB      56          2
    Customer1   CC      4567        3

您现在可以在CTE中包含上述查询并应用FOR XML PATH以获得所需的结果:

;WITH CTE AS (
    ... above query here ...
)
SELECT Labels AS "@Label", [Days] AS "@Days", LabelValue AS "@value" 
FROM CTE
FOR XML PATH('Return'), root('ReturnsList') 

对于多个日期,客户可以通过适当使用GROUP BY子句来调整上述查询。

答案 1 :(得分:0)

select 'AA' as [Return/@Label],
       1    as [Return/@Days] ,
       T.AA as [Return/@Value],
       null,
       'BB' as [Return/@Label],
       2    as [Return/@Days] ,
       T.BB as [Return/@Value],
       null,
       'CC' as [Return/@Label],
       3    as [Return/@Days] ,
       T.CC as [Return/@Value],
       null
from table as T
for xml path('ReturnList');

结果:

<ReturnList>
  <Return Label="AA" Days="1" Value="234" />
  <Return Label="BB" Days="2" Value="56" />
  <Return Label="CC" Days="3" Value="4567" />
</ReturnList>
<ReturnList>
  <Return Label="AA" Days="1" Value="55" />
  <Return Label="BB" Days="2" Value="66" />
  <Return Label="CC" Days="3" Value="77" />
</ReturnList>