set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
-- =============================================
-- Author: <Anncesky>
-- Create date: <2008/3/16>
-- Description: <Paged>
-- =============================================
ALTER PROCEDURE [dbo].[usp_pagination]
@tableName varchar(255), -- 表名
@colName varchar(255)='*', -- 字段名串
@pageSize int = 10, -- 页尺寸
@currentPage int = 1, -- 页码
@orderStr varchar(255) = '',-- 排序类型字段串(不带order by,带asc,desc,必须的)
@whereStr varchar(255) = '',-- 查询条件 (注意: 不要加 where)
@recordCount int output
AS
BEGIN
SET NOCOUNT ON;
declare @sql nvarchar(4000)
declare @TotalPages int
--计算总记录数及总页数
set @sql = 'select @recordCount = count(*) from ' + @tableName + ' where 1=1 ' + @whereStr
exec sp_executesql @sql,N'@recordCount int output',@recordCount output
select @TotalPages=CEILING((@recordCount+0.0)/@PageSize)
--处理页数超出范围情况
if @currentPage<=0
set @currentPage = 1
if @currentPage>@TotalPages
set @currentPage = @TotalPages
set @sql = 'select '+ @colName + ' from (select top(@currentPage*@pageSize) ' + @colName + ',row_number() over(order by ' + @orderStr + ') as rowNumber from ' + @tableName + ' where 1=1 ' + @whereStr + ') t where t.rowNumber >= ((@currentPage-1)*@pageSize+1)'
--print @Sql
exec sp_executesql @sql,N'@currentPage int, @pageSize int',@currentPage,@pageSize
END
玩技术,要学会忍受寂寞--