SQL Server通用分页存储过程,用存储过程可以提高效率与节约时间。
IF EXISTS(SELECT * FROM SYSOBJECTS WHERE name = 'commonPagination') DROP PROC commonPagination GO CREATE proc [dbo].[commonPagination] @columns varchar(500), --要显示的列名,用逗号隔开 @tableName varchar(100), --要查询的表名 @orderColumnName varchar(100), --排序的列名 @order varchar(50), --排序的方式,升序为asc,降序为 desc @where varchar(100), --where 条件,如果不带查询条件,请用 1=1 @pageIndex int, --当前页索引 @pageSize int, --页大小(每页显示的记录条数) @pageCount int output --总页数,输出参数 as begin declare @sqlRecordCount nvarchar(1000) --得到总记录条数的语句 declare @sqlSelect nvarchar(1000) --查询语句 set @sqlRecordCount=N'select @recordCount=count(*) from ' +@tableName + ' where '+ @where declare @recordCount int --保存总记录条数的变量 exec sp_executesql @sqlRecordCount,N'@recordCount int output',@recordCount output --动态 sql 传参 if( @recordCount % @pageSize = 0) --如果总记录条数可以被页大小整除 set @pageCount = @recordCount / @pageSize --总页数就等于总记录条数除以页大小 else --如果总记录条数不能被页大小整除 set @pageCount = @recordCount / @pageSize + 1 --总页数就等于总记录条数除以页大小加1 set @sqlSelect = N'select '+@columns+' from ( select row_number() over (order by ' +@orderColumnName+' '+@order +') as tempid,* from ' +@tableName+' where '+ @where +') as tempTableName where tempid between ' +str((@pageIndex - 1)*@pageSize + 1 ) +' and '+str( @pageIndex * @pageSize) exec (@sqlSelect) --执行动态Sql end
--以下是调用示例
use pubs
go
declare @pageCount int
exec commonPagination
'job_id,job_desc','jobs','job_id',
'asc','1=1',2,2,@pageCount output
select '总页数为:' + str(@pageCount)
IF EXISTS(SELECT * FROM SYSOBJECTS WHERE name = 'Pagination') DROP PROCEDURE Pagination GO CREATE PROCEDURE Pagination @Columns VARCHAR(500), -- The columns to be displayed, divide by comma @Tablename VARCHAR(100), -- The name of the table to be searched @OrderColumnName VARCHAR(100), -- The name of the column to be used in order @Order VARCHAR(50), -- The order method, ASC or DESC @Where VARCHAR(100), -- The where condition, if there is not conditon use 1=1 @PageIndex INT, -- Current page index @PageSize INT, -- The size of the page @PageCount INT OUTPUT -- The total page count,define as output parameter AS BEGIN DECLARE @SqlRecordCount NVARCHAR(100) -- The SQL Statement to get the total count of the records DECLARE @SqlSelect NVARCHAR(1000) -- The SQL SELECT statment SET @SqlRecordCount = N'SELECT @RecordCount = COUNT(*) FROM' + @Tablename + ' WHERE ' +@Where DECLARE @RecordCount INT EXEC sp_executesql @SqlRecordCount, N'@RecordCount INT OUTPUT',@RecordCount OUTPUT -- Transfer the parameter dynamic IF(@RecordCount % @PageSize = 0) SET @PageCount = @RecordCount / @PageSize ELSE SET @PageCount = @RecordCount / @PageSize + 1 SET @SqlSelect = N'SELECT ' + @Columns + ' FROM(SELECT ROW_NUMBER() OVER (ORDER BY ' + @OrderColumnName +' ' + @Order + ') AS tempid, * FROM ' + @Tablename + ' WHERE ' + @Where + ') AS tempTableName WHERE tempid BETWEEN ' + STR((@PageIndex - 1)*@PageSize + 1) + ' AND ' + STR(@PageIndex * @PageSize) EXEC (@SqlSelect) END GO