SQL Server For XML Query

时间:2013-11-24 02:42:13

标签: sql sql-server xml sqlxml

我的表格结构如下:

   date             Id        Value
   --------------------------------
   01/01/2005    50000        5              
   01/01/2006    50000        6   
   01/01/2007    50000        7   
   01/01/2005    50001        8   
   01/01/2006    50001        9   
   01/01/2007    50001        10

我想在SQL Server中使用for xml以下列格式输出xml:

<Date date = "01/01/2005"> <Id dealId=50000" value="5"/> <Id dealId=50001" value="8"/> </Date> <Date date = "01/01/2006"> <Id dealId=50000" value="6"/> <Id dealId=50001" value="9"/> </Date>

如果有人可以帮我解决SQL Server中的查询,那将会很有帮助。我自己尝试了几种,但我没有得到确切的输出。

2 个答案:

答案 0 :(得分:2)

-- using your provided values:
DECLARE @table TABLE ([date] DATE, id INT, value INT);
INSERT @Table VALUES ('01/01/2005',50000,5);
INSERT @Table VALUES ('01/01/2006',50000,6);
INSERT @Table VALUES ('01/01/2007',50000,7);
INSERT @Table VALUES ('01/01/2005',50001,8);
INSERT @Table VALUES ('01/01/2006',50001,9);
INSERT @Table VALUES ('01/01/2007',50001,10);

-- XML Query
-- the outer query groups by date, ensuring each date only shows up once
SELECT 
    [date] AS '@date',
    (
        -- The inner query selects all Ids for each date found in the outer query
        SELECT  id as '@dealId',
                value as '@value'
        FROM @Table B
        WHERE B.date=A.date -- join on date from outer query
        FOR XML PATH ('Id'), TYPE
    )
FROM @Table A
GROUP BY date
FOR XML PATH ('Date');

-- Produces:    
<Date date="2005-01-01">
    <Id dealId="50000" value="5"/>
    <Id dealId="50001" value="8"/>
</Date>
<Date date="2006-01-01">
    <Id dealId="50000" value="6"/>
    <Id dealId="50001" value="9"/>
</Date>
<Date date="2007-01-01">
    <Id dealId="50000" value="7"/>
    <Id dealId="50001" value="10"/>
</Date>

答案 1 :(得分:0)

通常,如果我需要这样一个简单的xml转换,我正在使用for xml raw

select
    t1.[date],
    (
        select
            t2.[Id] as dealId, t2.[Value]
        from Table1 as t2
        where t2.[date] = t1.[date]
        for xml raw('Id'), type
    )
from Table1 as t1
group by t1.[date]
for xml raw('Date')

----------------------
<Date date="2005-01-01">
    <Id dealId="50000" Value="5"/>
    <Id dealId="50001" Value="8"/>
</Date>
<Date date="2006-01-01">
    <Id dealId="50000" Value="6"/>
    <Id dealId="50001" Value="9"/>
</Date>
<Date date="2007-01-01">
    <Id dealId="50000" Value="7"/>
    <Id dealId="50001" Value="10"/>
</Date>

sql fiddle demo

中自行尝试

一些注意事项:

  • 您不必在列名中使用 @,因为默认情况下for xml raw是以属性为中心的。
  • 子查询这里是必要的,因为你想要嵌套的xml,现在它是获得它的唯一方法。
  • 您还必须在子查询中使用type修饰符将内部数据作为xml。