如何在子查询中使用FOR XML?

时间:2012-07-30 12:07:04

标签: sql sql-server xml for-xml

我想返回以下xml:

<ResultDetails>
<Node1>hello</Node1>
<Sites>
<Site><SiteId>1</SiteId></Site>
<Site><SiteId>2</SiteId></Site>
</Sites>
</ResultDetails>

我写了下面的代码,但不起作用:

SELECT 'hello' AS Node1,    
    (SELECT TOP 2 SiteId
     FROM [dbo].[Sites]
       FOR XML PATH('Site')) AS Sites
FOR XML PATH('ResultDetails')

但它返回:

<ResultDetails>
  <row>
    <Node1>hello</Node1>
    <Sites>&lt;Site&gt;&lt;siteId&gt;102&lt;/siteId&gt;&lt;/Site&gt;&lt;Site&gt;&lt;siteId&gt;1&lt;/siteId&gt;&lt;/Site&gt;</Sites>
  </row>
</ResultDetails>

我应该写什么SQL?

感谢,

1 个答案:

答案 0 :(得分:14)

您需要将TYPE修饰符添加到内部查询中:

SELECT
    'hello' AS Node1
    , (
        SELECT TOP 2 SiteId 
            FROM [dbo].[Sites] 
        FOR XML PATH('Site'), TYPE
    ) AS Sites 
FOR XML PATH('ResultDetails')