作者:用户24fbqhclmt | 来源:互联网 | 2024-11-21 17:23
在处理大量数据时,分页查询是一种常见的需求。本文将通过一个具体的SQL Server存储过程示例,展示如何实现基于单一条件的分页查询。
CREATE PROCEDURE [dbo].[Pagination_SingleCondition] (
@TableName NVARCHAR(255),
@SelectColumns NVARCHAR(1000) = '*',
@WhereCondition NVARCHAR(1000) = '',
@OrderByColumn NVARCHAR(255) = '',
@OrderType INT = 0,
@PageSize INT = 10,
@PageIndex INT = 1,
@ShowPageCount BIT = 0,
@ShowRecordCount BIT = 0,
@TotalRecords INT OUTPUT,
@TotalPages INT OUTPUT
) AS
BEGIN
DECLARE @MainQuery NVARCHAR(MAX);
DECLARE @TempVar NVARCHAR(100);
DECLARE @OrderByClause NVARCHAR(400);
SET @TotalRecords = 0;
SET @TotalPages = 0;
IF @ShowRecordCount = 1 OR @ShowPageCount = 1
BEGIN
IF LEN(@WhereCondition) > 0
SET @MainQuery = 'SELECT @TotalRecords = COUNT(*) FROM [' + @TableName + '] WHERE ' + @WhereCondition;
ELSE
SET @MainQuery = 'SELECT @TotalRecords = COUNT(*) FROM [' + @TableName + ']';
EXEC sp_executesql @MainQuery, N'@TotalRecords INT OUT', @TotalRecords OUT;
END
IF @ShowPageCount = 1
BEGIN
IF @TotalRecords <= @PageSize
SET @TotalPages = 1;
ELSE
BEGIN
SET @TotalPages = @TotalRecords / @PageSize;
IF (@TotalRecords % @PageSize) > 0
SET @TotalPages = @TotalPages + 1;
END
END
IF @OrderType = 1
BEGIN
SET @TempVar = '(SELECT MIN(';
SET @OrderByClause = ' ORDER BY [' + @OrderByColumn + '] DESC';
END
ELSE
BEGIN
SET @TempVar = '(SELECT MAX(';
SET @OrderByClause = ' ORDER BY [' + @OrderByColumn + '] ASC';
END
IF @PageIndex = 1
BEGIN
IF LEN(@WhereCondition) > 0
SET @MainQuery = 'SELECT TOP ' + CAST(@PageSize AS NVARCHAR(10)) + ' ' + @SelectColumns + ' FROM [' + @TableName + '] WHERE ' + @WhereCondition + ' ' + @OrderByClause;
ELSE
SET @MainQuery = 'SELECT TOP ' + CAST(@PageSize AS NVARCHAR(10)) + ' ' + @SelectColumns + ' FROM [' + @TableName + '] ' + @OrderByClause;
END
ELSE
BEGIN
IF LEN(@WhereCondition) > 0
SET @MainQuery = 'SELECT TOP ' + CAST(@PageSize AS NVARCHAR(10)) + ' ' + @SelectColumns + ' FROM [' + @TableName + '] WHERE [' + @OrderByColumn + ']' + @TempVar + '[' + @OrderByColumn + ']) FROM (SELECT TOP ' + CAST((@PageIndex - 1) * @PageSize AS NVARCHAR(10)) + ' [' + @OrderByColumn + '] FROM [' + @TableName + '] WHERE ' + @WhereCondition + ' ' + @OrderByClause + ') AS TempTable) AND ' + @WhereCondition + ' ' + @OrderByClause;
ELSE
SET @MainQuery = 'SELECT TOP ' + CAST(@PageSize AS NVARCHAR(10)) + ' ' + @SelectColumns + ' FROM [' + @TableName + '] WHERE [' + @OrderByColumn + ']' + @TempVar + '[' + @OrderByColumn + ']) FROM (SELECT TOP ' + CAST((@PageIndex - 1) * @PageSize AS NVARCHAR(10)) + ' [' + @OrderByColumn + '] FROM [' + @TableName + '] ' + @OrderByClause + ') AS TempTable) ' + @OrderByClause;
END
EXEC (@MainQuery);
END
调用示例:EXEC dbo.Pagination_SingleCondition 'UserDetails', '*', '', 'UserID', 1, 10, 1, 1, @TotalRecords OUT, @TotalPages OUT;
上述存储过程的主要逻辑如下:
- 首先计算总记录数和总页数(如果需要)。
- 根据分页索引和页面大小构造主查询。
- 如果当前页不是第一页,则需要从上一页的最后一个记录开始查询。
- 最后执行主查询以获取当前页的数据。
通过这种方式,可以有效地实现基于单一条件的分页查询,提高查询效率和用户体验。