在article here的帮助下以及SO专家最近的回答中,我得到了以下内容,这将有助于我有效地翻阅一组记录。
我认为我的最后几个问题是
Total Number of Records
SQL CTE称为“总计”。这是你怎么做的? Return Total Number of Pages
DECLARE @page_size INT = 5;
DECLARE @page_nbr INT = 4;
DECLARE @search NVARCHAR(MAX) = '';
DECLARE @sort_order INT = 2;
WITH AllProducts
AS
(
SELECT *,
CASE @sort_order
WHEN 1 THEN ROW_NUMBER() OVER ( ORDER BY ProductID )
WHEN 2 THEN ROW_NUMBER() OVER ( ORDER BY ProductName )
END AS 'Seq'
FROM Products
),
Filtered
AS
(
SELECT * FROM AllProducts
WHERE ProductName like '%'+@search+'%'
OR
@search is null
)
SELECT (select COUNT(*) from Filtered) as 'Total', * FROM Filtered
WHERE seq > (@page_nbr - 1) * @page_size
AND seq <= @page_nbr * @page_size
答案 0 :(得分:1)
我认为您的查询有问题:它会记录(用于分页),然后应用过滤器。
例如,您可以请求记录的第2页,但同时可以过滤掉所有具有相应seq
值的记录。因此,在这种情况下,查询不会产生任何结果,尽管表中可能有大量记录。
为了解决这个问题,你可以在同一个CTE中进行过滤和记录编号,如下所示:
DECLARE @page_size INT = 5;
DECLARE @page_nbr INT = 4;
DECLARE @search NVARCHAR(MAX) = '';
DECLARE @sort_order INT = 2;
WITH Filtered AS (
SELECT *,
CASE @sort_order
WHEN 1 THEN ROW_NUMBER() OVER ( ORDER BY ProductID )
WHEN 2 THEN ROW_NUMBER() OVER ( ORDER BY ProductName )
END AS 'Seq'
FROM AllProducts
WHERE ProductName like '%'+@search+'%' OR @search is null
)
SELECT (select COUNT(*) from Filtered) as 'Total', * FROM Filtered
WHERE seq > (@page_nbr - 1) * @page_size
AND seq <= @page_nbr * @page_size