计算没有限制的总行数

时间:2011-04-16 12:03:49

标签: sql stored-procedures full-text-search for-xml

目前正在运行,但我希望xml包含没有限制的总行数。

SET @query_result = (SELECT ID,Title 
        FROM
        ( 
            SELECT items.id AS "ID",items.title AS "Title" ,
ROW_NUMBER() OVER(ORDER BY date_added DESC) AS RowNum
                FROM [cars] 
                JOIN [items] ON items.id=cars.item_id
                WHERE
                rejected = 0 


    )AS MyDerivedTable
        WHERE
        MyDerivedTable.RowNum BETWEEN (@page-1)*2+1 AND (@page*2) 
        FOR XML PATH('car'),ROOT('items')
)

返回

<items>
  <car>
    <ID>37</ID>
    <Title>Used 2004 Chevrolet Corvette Convertible</Title>
  </car>
</items>

我想要

<items>
      <car>
        <ID>37</ID>
        <Title>Used 2004 Chevrolet Corvette Convertible</Title>
        <Count>6</Count>
      </car>
    </items>

虽然Count不是返回的行数,但是与查询匹配的行总数。或者如果我的问题太难以让任何人理解,我正在寻找FOUND_ROWS()的MSSQL替代方法。 这个问题@ SQL Count total number of rows whilst using LIMIT试图回答同样的问题,但我想要一个解决方案是MSSQL。

1 个答案:

答案 0 :(得分:2)

好的,我希望我现在明白你要做的事情。我相信你必须“转身”你的选择并使用CTE(通用表格表达式)代替子选择来实现这一点。

试试这个:

DECLARE @queryResult VARCHAR(MAX)

;WITH MyDerivedTable AS
(
    SELECT 
       items.id,
       items.title,
       ROW_NUMBER() OVER(ORDER BY date_added DESC) AS RowNum
    FROM dbo.cars
    INNER JOIN dbo.items ON items.id = cars.item_id
    WHERE rejected = 0 
) 
SELECT
   @queryResult = 
   (SELECT
       ID, Title,
       (SELECT MAX(RowNum) FROM MyDerivedTable) AS 'Count'
    FROM
       MyDerivedTable
    WHERE
        RowNum BETWEEN (@page-1)*2+1 AND (@page*2) 
    FOR XML PATH('car'),ROOT('items')
   )

SELECT @queryResult

应为每个车辆输入IDTitleCountRowNum的最大值)。