使用FOR XML PATH向根元素添加计数

时间:2015-09-15 12:23:07

标签: sql-server xml for-xml-path

我有一个Sql语句,它返回xml的产品,其中根元素是产品。如何将count属性添加到根元素。

我的sql是:

SELECT 
id AS 'product_id',
name AS 'product_name'
 FROM product
WHERE status = 1 AND ......
ORDER BY productid
FOR XML PATH('product'), ROOT('products')

结果是

<products>
   <product>
    .
    .
   </product>
</products>

我想将结果更改为

<products count="100">
   <product>
    .
    .
   </product>
</products>

1 个答案:

答案 0 :(得分:4)

SELECT 
COUNT(*) AS '@count',
(
    SELECT * 
    FROM product c1 FOR XML PATH('product'), TYPE
)
FROM product ct FOR XML PATH('products')

最简单的过滤方法是在查询和子查询中添加条件:

SELECT 
COUNT(*) AS '@count',
(
    SELECT * 
    FROM product c1 
    WHERE c1.status = 1 AND ......
    FOR XML PATH('product'), TYPE
)
FROM product ct 
WHERE ct.status = 1 AND ......
FOR XML PATH('products')

或者使用temp-table:

SELECT *
INTO #Temp
FROM product c1
WHERE c1.status = 1 AND ......


SELECT 
COUNT(*) AS '@count',
(
    SELECT * 
    FROM #Temp c1 
    FOR XML PATH('product'), TYPE
)
FROM #Temp ct 
FOR XML PATH('products')