if exists (select name from sysobjects where name =''sp_page'')
drop proc sp_page
go
create proc sp_page
@strTable varchar(50), --表名
@strColumn varchar(50), --按该列来进行分页
@intColType int, --@strColumn列的类型,0-数字类型,1-字符类型,2-日期时间类型
@intOrder bit, --排序,0-顺序,1-倒序
@strColumnlist varchar(800), --要查询出的字段列表,*表示全部字段
@intPageSize int, --每页记录数
@intPageNum int, --指定页
@strWhere varchar(800), --查询条件
@intPageCount int output --总页数
as
declare @sql nvarchar(4000) --用于构造SQL语句
declare @where1 varchar(800) --构造条件语句
declare @where2 varchar(800) --构造条件语句
if @strWhere is null or rtrim(@strWhere)=''''
-- 为了避免SQL关键字与字段、表名等连在一起,首先为传入的变量添加空格
begin --没有查询条件
set @where1='' where ''
set @where2='' ''
end
else
begin --有查询条件
set @where1='' where (''+@strWhere+'') and ''
set @where2='' where (''+@strWhere+'') ''
end
set @strColumn = '' '' + @strColumn + '' ''
set @strColumnlist = '' '' + @strColumnlist + '' ''
--构造SQL语句,计算总页数。计算公式为 总页数 = Ceiling ( 记录个数 / 页大小 )
set @sql=''select @intPageCount=ceiling((count(*)+0.0)/''
+ cast(@intPageSize as varchar)
+ '') from '' + @strTable + @where2
--执行SQL语句,计算总页数,并将其放入@intPageCount变量中
exec sp_executesql @sql,N''@intPageCount int output'',@intPageCount output
--将总页数放到查询返回记录集的第一个字段前,此语句可省略
--set @strColumnlist = cast(@intPageCount as varchar(30)) + '' as PageCount,'' + @strColumnlist
if @intOrder=0 --构造升序的SQL
set @sql=''select top ''+ cast(@intPageSize as varchar) +
@strColumnlist +
'' from '' + @strTable + @where1 +
@strColumn + ''>(select max(''+@strColumn+'') ''+
'' from (select top ''+ cast(@intPageSize*(@intPageNum - 1) as varchar) +
@strColumn + '' from ''+ @strTable+@where2+''order by ''+@strColumn+'') t) order by ''+ @strColumn
else --构造降序的SQL
set @sql=''select top ''+ cast(@intPageSize as varchar) +
@strColumnlist+
'' from ''+ @strTable + @where1 +
@strColumn + ''<(select min(''+@strColumn+'') ''+
'' from (select top ''+ cast(@intPageSize*(@intPageNum - 1) as varchar) +
@strColumn + '' from ''+ @strTable+@where2+''order by ''+@strColumn+'' desc) t) order by ''+
@strColumn + '' desc''
if @intPageNum=1 --第一页
set @sql=''select top ''+cast(@intPageSize as varchar) + @strColumnlist + '' from ''+@strTable+
@where2+''order by '' + @strColumn + case @intOrder when 0 then '''' else '' desc''
end
--PRINT @sql
exec(@sql)
go
declare @intPageCount int
exec sp_page ''Alarm1'',''Id'',0,0,''*'',20,1,'''',@intPageCount output
drop proc sp_page