SQL 高效的万能分页语句

Posted null

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL 高效的万能分页语句相关的知识,希望对你有一定的参考价值。

代码如下:

USE [Blog]
IF OBJECT_ID(Proc_Paging, P) IS NOT NULL    --删除同名存储过程
    DROP PROC Proc_Paging
GO
CREATE PROC Proc_Paging
    @TableFields NVARCHAR(512),
    @TableName NVARCHAR(512),
    @SqlWhere NVARCHAR(512),
    @OrderBy NVARCHAR(64),
    @PageIndex INT,
    @PageSize INT,
    @TotalCount INT OUTPUT
AS
    DECLARE @SQL1 NVARCHAR(2048), @SQL2 NVARCHAR(2048)    --@SQL1和@SQL2最好设置为比较长的字符串,否则会因为SQL语句过长而导致执行失败
    --SET @SQL1 = N‘SELECT TOP ‘ + CONVERT(VARCHAR(2), @PageSize) + ‘ * FROM (SELECT ROW_NUMBER() OVER(ORDER BY ‘ + @OrderBy + ‘) AS NID, ‘ + @TableFields + ‘ FROM ‘ + @TableName + ‘ WHERE ‘ + @SqlWhere + ‘) AS TmpTable WHERE TmpTable.NID > (@PageIndex - 1) * @PageSize‘  --用TOP关键字进行筛选
    SET @SQL1 = NSELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY  + @OrderBy + ) AS NID,  + @TableFields +  FROM  + @TableName +  WHERE  + @SqlWhere + ) AS TmpTable WHERE TmpTable.NID BETWEEN (@PageIndex - 1) * @PageSize + 1 AND @PageIndex* @PageSize
    SET @SQL2 = N@TableFields NVARCHAR(512),@TableName NVARCHAR(512),@SqlWhere NVARCHAR(512),@OrderBy NVARCHAR(64),@PageIndex INT,@PageSize INT,@TotalCount INT OUTPUT
EXEC SP_EXECUTESQL @SQL1, @SQL2, @TableFields, @TableName, @SqlWhere,@OrderBy,@PageIndex,@PageSize,@TotalCount OUTPUT
PRINT @SQL1    --打印执行语句  

GO    --测试用例
DECLARE @Count INT = 0
EXEC Proc_Paging *, POSTS, PublishTime < GETDATE(), Id, 5, 10, @Count OUTPUT    --筛选发布时间小于当前时间的记录

【注意点】:@SQL1和@SQL2最好设置为比较长的字符串,否则会因为SQL语句过长而导致执行失败

以上是关于SQL 高效的万能分页语句的主要内容,如果未能解决你的问题,请参考以下文章

Sql万能分页代码

使用with as高效分页

oracle 高效分页查询SQL

OracleDB2SQLSERVERMysqlAccess分页SQL语句

案例分析:SQL 窗口函数实现高效分页查询

mysql分页原理和高效率的mysql分页查询语句