向SQL XML添加一个节点显式结果

时间:2015-04-18 18:45:20

标签: sql sql-server xml

我想在我的元素底部添加一个节点,这是SQL查询的结果(对于xml显式)。

这是我的问题:

SELECT 1 AS Tag,
   NULL AS Parent,
   ROW_NUMBER() OVER
     (
        ORDER BY c.SubCategoryID ASC
     )AS [Customers!1!RowNumber!ELEMENT],
   c.SubCategoryID AS [Customers!1!SubCategoryID!ELEMENT],
   c.Name AS [Customers!1!Name!ELEMENT],
   x.Description AS [Customers!1!Description!ELEMENT], 
   x.Image AS [Customers!1!Image!ELEMENT] 
FROM (SELECT TOP(3) * FROM tSubCategory) c 
CROSS APPLY
(
    SELECT TOP(3) *
    FROM tProduct p
    WHERE c.SubCategoryID = p.SubCategoryID
    ORDER BY p.ProductID DESC
) x 
FOR XML EXPLICIT;

这是我的结果:

<Customers>
  <RowNumber>1</RowNumber>
  <SubCategoryID>1</SubCategoryID>
  <Name>John</Name>
  <Description>xtz</Description>
  <Image>ips.png</Image>
</Customers>
<Customers>
  <RowNumber>2</RowNumber>
  <SubCategoryID>1</SubCategoryID>
  <Name>Alex</Name>
  <Description>sdgfgsg</Description>
  <Image>ne2.jpg</Image>
</Customers>

在上面结果的底部,我想只添加一个节点:

<Test>
   <Test>1</Test>
</Test>

我该怎么做?另外,我如何将上述所有结果包含在以下内容中:

<AllResults>
</AllResults>

1 个答案:

答案 0 :(得分:0)

我相信我在下面找到了答案。如果有人想发表评论,请做。

 SELECT 
    (
    SELECT 2 AS Tag,
       NULL AS Parent,  
       ROW_NUMBER() OVER
         (
            ORDER BY c.SubCategoryID ASC
         )AS [Customers!2!RowNumber!ELEMENT],
       c.SubCategoryID AS [Customers!2!SubCategoryID!ELEMENT],
       c.Name AS [Customers!2!Name!ELEMENT],
       x.Description AS [Customers!2!Description!ELEMENT], 
       x.Image AS [Customers!2!Image!ELEMENT]
    FROM (SELECT TOP(3) * FROM tSubCategory) c 
    CROSS APPLY
    (
        SELECT TOP(3) *
        FROM tProduct p
        WHERE c.SubCategoryID = p.SubCategoryID
        ORDER BY p.ProductID DESC
    ) x 
    FOR XML EXPLICIT, TYPE
    ), 1 as test
    FOR XML PATH ('AllResults'), TYPE