我想返回以下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><Site><siteId>102</siteId></Site><Site><siteId>1</siteId></Site></Sites>
</row>
</ResultDetails>
我应该写什么SQL?
感谢,
答案 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')