假设数据库中有张表,表名是username,字段分别是id(int),name(nvarchar),age(int)。
如果不带查询条件存储过程是:
复制代码 代码如下:
create procedure [dbo].[username]
@pageindex int,
@pagesize int
as
declare @min int;
declare @max int;
set @min=@pagesize*(@pageindex-1)+1;
set @max=@pagesize*@pageindex;
with mytable as(select id,name,age,row_number() over (order by id) as rownum from [username] )
select id,name,age from mytable where rownum between @min and @max
return
这个分页存储过程很不实用,并且表是固定的。
下面十二个万能分页存储过程,
复制代码 代码如下:
create procedure [dbo].[up_getrecordbypage]
@tblname varchar(255), — 表名
@fldname varchar(255), — 主键字段名
@pagesize int , — 页尺寸
@pageindex int , — 页码
@isrecount bit, — 返回记录总数, 非 0 值则返回
@ordertype bit, — 设置排序类型, 非 0 值则降序
@strwhere varchar(1000) = ” — 查询条件 (注意: 不要加 where)
as
declare @strsql varchar(6000) — 主语句
declare @strtmp varchar(2000) — 临时变量(查询条件过长时可能会出错,可修改100为1000)
declare @strorder varchar(400) — 排序类型
if @ordertype != 0
begin
set @strtmp = ‘<(select min’
set @strorder = ‘ order by [‘ + @fldname +’] desc’
end
else
begin
set @strtmp = ‘>(select max’
set @strorder = ‘ order by [‘ + @fldname +’] asc’
end
set @strsql = ‘select top ‘ + str(@pagesize) + ‘ * 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) + ‘ * from [‘
+ @tblname + ‘] where [‘ + @fldname + ‘]’ + @strtmp + ‘([‘
+ @fldname + ‘]) from (select top ‘ + str((@pageindex-1)*@pagesize) + ‘ [‘
+ @fldname + ‘] from [‘ + @tblname + ‘] where ‘ + @strwhere + ‘ ‘
+ @strorder + ‘) as tbltmp) and ‘ + @strwhere + ‘ ‘ + @strorder
if @pageindex <> 0
begin
set @strtmp =”
if @strwhere != ”
set @strtmp = ‘ where ‘ + @strwhere
set @strsql = ‘select top ‘ + str(@pagesize) + ‘ * from [‘
+ @tblname + ‘]’ + @strtmp + ‘ ‘ + @strorder
exec (@strsql)
end
if @isrecount != 0
begin
set @strsql = ‘select count(*) as total from [‘ + @tblname + ‘]’+’ where ‘ + @strwhere
exec (@strsql)
end
使用方法:
复制代码 代码如下:
exec dbo.up_getrecordbypage @tblname = ‘username’, — varchar(255)
@fldname = ‘id’, — varchar(255)
@pagesize = 2, — int
@pageindex = 1, — int
@isrecount = 0, — bit
@ordertype = 1, — bit
@strwhere = ‘age=13’ — varchar(1000)
如果哪里有不正确的地方,欢迎批评指正,共同进步。