USE [test]
GO
/****** Object: StoredProcedure [dbo].[procCommonPaging] Script Date: 03/22/2012 13:34:59 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/* 功能:带分页的存储过程,只支持单表
* 姓名:
* 日期:
*/
CREATE PROCEDURE [dbo].[procCommonPaging]
@pagesize int, --显示的大小
@pageindex int,--传入的页码
@keyFiled varchar(50),--主键字段
@tablename varchar(150),--表名
@condition varchar(500),--查询条件
@sort varchar(150),--排序
@rowcount int output,--查询的总记录数
@pagecount int output --获得总页码
AS
-- 查询的总记录数
declare @sql nvarchar(4000)--要执行的SQl
declare @expellent int--要排除的记录数
begin
--获取总记录数
set @sql = 'select @rowcount = count(*) from ' + @tablename+' '+@condition
EXEC sp_executesql @sql,N'@rowcount int output',@rowcount output--计算总记录数
set @pagecount=CEILING((@rowcount*1.0)/@PageSize)--计算总页数
if @pageindex=1
begin
set @sql = 'select top '+str(@pagesize)+' * from ' + @tablename+' '+@condition+' '+@sort
end
begin
if @condition=' '
begin
set @expellent=@pagesize*(@pageIndex-1) --计算要排除的记录数
set @sql = 'select top '+str(@pagesize)+' * from ' + @tablename+' where '+@keyFiled+' not in(select top '+STR(@expellent)+' '+@keyFiled+' from '+@tablename+' '+@sort+ ') '+@sort
end
else
begin
set @expellent=@pagesize*(@pageIndex-1)--计算要排除的记录数
set @sql = 'select top '+str(@pagesize)+' * from ' + @tablename+' '+@condition+' and '+@keyFiled+' not in(select top '+STR(@expellent)+' '+@keyFiled+' from '+@tablename+' '+@condition+' '+@sort+') '+@sort
end
end
exec(@sql)
end
GO