通用分页存储过程
create procedure pagination
@tblname varchar(255), -- 表名
@strgetfields varchar(1000) = '*', -- 需要返回的列
@fldname varchar(255)='', -- 排序的字段名
@pagesize int = 10, -- 页尺寸
@pageindex int = 1, -- 页码
@docount bit = 0, -- 返回记录总数, 非 0 值则返回
@ordertype bit = 0, -- 设置排序类型, 非 0 值则降序
@strwhere varchar(1500) = '' -- 查询条件 (注意: 不要加 where)
as
declare @strsql varchar(5000) -- 主语句
declare @strtmp varchar(110) -- 临时变量
declare @strorder varchar(400) -- 排序类型
if @docount != 0
begin
if @strwhere !=''
set @strsql = 'select count(*) as total from [' + @tblname + '] where '[email protected]
else
set @strsql = 'select count(*) as total from [' + @tblname + ']'
end
--以上代码的意思是如果@docount传递过来的不是0,就执行总数统计。以下的所有代码都是@docount为0的情况
else
begin
if @ordertype != 0
begin
set @strtmp = '<(select min'
set @strorder = ' order by [' + @fldname +'] desc'
--如果@ordertype不是0,就执行降序,这句很重要!
end
else
begin
set @strtmp = '>(select max'
set @strorder = ' order by [' + @fldname +'] asc'
end
if @pageindex = 1
begin
if @strwhere != ''
set @strsql = 'select top ' + str(@pagesize) +' '[email protected]+ ' from [' + @tblname + '] where ' + @strwhere + ' ' + @strorder
else
set @strsql = 'select top ' + str(@pagesize) +' '[email protected]+ ' from ['+ @tblname + '] '+ @strorder
--如果是第一页就执行以上代码,这样会加快执行速度
end
else
begin
--以下代码赋予了@strsql以真正执行的sql代码
set @strsql = 'select top ' + str(@pagesize) +' '[email protected]+ ' from ['
+ @tblname + '] where [' + @fldname + ']' + @strtmp + '(['+ @fldname + ']) from (select top ' + str((@pageindex-1)*@pagesize) + ' ['+ @fldname + '] from [' + @tblname + ']' + @strorder + ') as tbltmp)'+ @strorder
if @strwhere != ''
set @strsql = 'select top ' + str(@pagesize) +' '[email protected]+ ' from ['
+ @tblname + '] where [' + @fldname + ']' + @strtmp + '(['
+ @fldname + ']) from (select top ' + str((@pageindex-1)*@pagesize) + ' ['
+ @fldname + '] from [' + @tblname + '] where ' + @strwhere + ' '
+ @strorder + ') as tbltmp) and ' + @strwhere + ' ' + @strorder
end
end
exec (@strsql)
go