假设数据库中有张表,表名是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)