-- 返回值:表1 - 查询的内容;表2 - 记录总数
-- 调用事例
--exec GetDataByPage 'select UserID,UserName','UserInfo','UserID desc',1,10
Create proc GetDataByPage
@SQL varchar(max), -- 要执行的SQL语句(from关键字前面的所有内容<即字段列表>)
@From varchar(max), -- from关键字后面的全部内容,包含多表连接查询
@OrderBy varchar(50), -- 用于排序的字段和排序方向(如:AddTime desc)
@PageIndex int, -- 当前页码
@PageSize int -- 每页显示的数量
as
begin
declare @Start int
declare @End int
declare @NewSQL varchar(max)
if @PageIndex = 1
begin
set @Start = 1
end
else
begin
set @Start = (@PageIndex - 1) * @PageSize + 1
end
set @NewSQL = 'select top ' + cast(@PageSize as varchar) +
' * from (' + @SQL + ',row_number() over(order by ' + @OrderBy + ') as RankID from ' + @From + ') as C where RankID between ' +
cast(@Start as varchar) + ' and ' + cast(@PageSize * 2 * @PageIndex as varchar)
exec(@NewSQL + ';select count(1) as TotalCount from ' + @From)
end
下载SQL文件:SQLSever分页存储过程.zip
ok
mjj通道