目前正在运行,但我希望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。
答案 0 :(得分:2)
试试这个:
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
应为每个车辆输入ID
,Title
和Count
(RowNum
的最大值)。