/*通用分页存储过程 MS SQL Server 2005*/ CREATE PROCEDURE Pagination ( @TableName VARCHAR(255), -- 表名/视图名 @SelectFields VARCHAR(1000) = '*', -- 需要返回的列 @Where VARCHAR(3000) = '1=1', -- 查询条件(注意: 不要加where) @OrderField VARCHAR(255)='', -- 排序字段 @PageSize INT = 10, -- 页尺寸 @PageIndex INT = 1, -- 当前页码(从第页开始) @RowCount INT OUTPUT -- 记录总数 ) AS BEGIN --定义变量,SQL语句 DECLARE @SQL_SELECT NVARCHAR(4000) DECLARE @SQL_COUNT NVARCHAR(4000) --统计总数据量 SET @SQL_COUNT = N'SELECT @RowCount= COUNT(*) FROM ' + @TableName + ' WHERE ' + @WHERE EXEC SP_EXECUTESQL @SQL_COUNT,N'@RowCount INT OUTPUT',@RowCount=@RowCount OUTPUT --执行分页查询 SET @SQL_SELECT = 'SELECT * FROM ( SELECT ROW_NUMBER() OVER(ORDER BY ' + @OrderField + ') AS RowNumber,' + @SelectFields + ' FROM ' + @TableName + ' WHERE ' + @Where + ' )AS TempTable WHERE RowNumber > ' + CONVERT(VARCHAR,(@PageIndex - 1) * @PageSize) + 'AND RowNumber <= ' + CONVERT(VARCHAR,@PageIndex * @PageSize) EXEC (@SQL_SELECT) END /*通用分页存储过程 MS SQL Server 2000*/ CREATE PROCEDURE Pagination ( @TableName VARCHAR(255), -- 表名/视图名 @SelectFields VARCHAR(1000) = '*', -- 需要返回的列 @PKField VARCHAR(255), -- 主键列 @Where VARCHAR(3000) = '1=1', -- 查询条件(注意: 不要加where) @OrderField VARCHAR(255)='', -- 排序字段 @PageSize INT = 10, -- 页尺寸 @PageIndex INT = 1, -- 当前页码(从第1页开始) @RowCount INT OUTPUT -- 记录总数 ) AS BEGIN --定义变量,SQL语句 DECLARE @SQL_SELECT NVARCHAR(4000) DECLARE @SQL_COUNT NVARCHAR(4000) --统计总数据量 SET @SQL_COUNT = N'SELECT @RC = COUNT(*) FROM ' + @TableName + ' WHERE ' + @WHERE EXEC SP_EXECUTESQL @SQL_COUNT,N'@RC INT OUTPUT',@RC=@RowCount OUTPUT --执行分页查询 SET @SQL_SELECT = 'SELECT TOP ' + CONVERT(VARCHAR,@PageSize) + ' ' + @SelectFields + ' FROM ' + @TableName + ' WHERE ' + @Where + ' AND ' + @PKField + ' NOT IN ( SELECT TOP ' + CONVERT(VARCHAR,(@PageIndex-1)*@PageSize) + ' '+ @PKField + ' FROM ' + @TableName + ' WHERE ' + @Where + ' ORDER BY ' + @OrderField + ' ) ORDER BY '+ @OrderField EXEC (@SQL_SELECT) END