复制代码 代码如下:
/*
数据库分页存储过程,支持倒序和升序
参数说明:
@tablename:为搜索表名
@tablefield:为表的字段,约定为表的主键,
@where:为搜索表名,要显示所有记录请设为”1=1″
@orderby:为搜索结果排序,如order by id desc
@fieldlist:为字段列表,如userid, username
@curpage:当前页码
@page_record:每页记录条数
@sort:排序标识(如果是倒序排,参数值为desc,为升序,参数值为asc,跟orderby参数是对应的)
结果: 返回表tablename中满足条件where的第curpage页的page_record条记录,结果按orderby排序
*/
create procedure proc_commonpaging
@tablename varchar(100),
@tablefield varchar(20),
@where varchar(5000),
@orderby varchar(500),
@fieldlist varchar(1000),
@curpage int,
@page_record int,
@sort varchar(8)
as
begin
declare @cmd varchar(8000)
declare @uprecord int
declare @op varchar(2) — 操作符
declare @max_min varchar(4) — 最大/最小计算
set @op = ‘<‘
set @max_min = ‘min’
if @sort = ‘asc’
begin
set @op = ‘>’
set @max_min = ‘max’
end
set @uprecord=@curpage * @page_record
if @curpage = 0
set @cmd = ‘select top ‘+cast(@page_record as nvarchar)+’ ‘+@fieldlist+’ from ‘+@tablename+’ where ‘+@where+’ ‘+@orderby
else
set @cmd = ‘select top ‘+cast(@page_record as nvarchar)+’ ‘+@fieldlist+’ from ‘+@tablename+’ where ‘+@where+’ and ‘+@tablefield+’
‘+@op+’ (select ‘+@max_min+'(‘+@tablefield+’) from (select top ‘+cast(@uprecord as nvarchar)+’ ‘+@tablefield+’ from ‘+@tablename+’ where
‘+@where+’ ‘+@orderby+’) as tmptbl ) and ‘+@where+’ ‘+@orderby
set @cmd = @cmd + ‘; select count(*) from ‘+@tablename+’ where ‘+@where
exec(@cmd)
print(@cmd)
end
go