SQL分页查询过程
CREATE PROCEDURE [dbo].[sp_GetPageData]
@TableName NVARCHAR(max), -- 表名
@GetFields NVARCHAR(max) = '*', -- 字段名(全部字段为*)
@OrderField NVARCHAR(max), -- 排序字段(必须!支持多字段)
@WhereCondition NVARCHAR(max) = Null, -- 条件语句(不用加where)
@PageIndex int = 1 , -- 指定当前为第几页
@PageSize int = 20, -- 每页多少条记录
@GroupBy varchar(800), --分组语句(不用加Group by)
@RecordCount int = 0 output --返回总记录条数
as begin
declare @PageCount int -- 返回总页数
set @PageCount = 0
--- Begin Tran --开始事务
Declare @sql nvarchar(max);
--计算总记录数
if(@GroupBy ='' or @GroupBy is null) --无GroupBy的情况
begin
set @sql = 'select @RecordCount = count(1) from ' + @TableName
if (@WhereCondition<>'' and @WhereCondition is not NULL)
set @sql = @sql + ' where ' + @WhereCondition
end
else --有GroupBy的情况
begin
set @sql = 'select @Recordcount=count(1) from(select 1 as total from ' + @TableName
if (@WhereCondition<>'' and @WhereCondition is not NULL)
set @sql = @sql + ' where ' + @WhereCondition
set @sql = @sql + ' group by ' + @GroupBy
set @sql = @sql + ') as t'
end
EXEC sp_executesql @sql,N'@RecordCount int OUTPUT',@RecordCount OUTPUT--计算总记录数
select @PageCount=CEILING((@RecordCount+0.0)/@PageSize) --计算总页数
set @sql = 'Select * FROM (select ROW_NUMBER() Over(order by ' + @OrderField + ') as rowId,' + @GetFields + ' from ' + @TableName
if (@WhereCondition<>'' and @WhereCondition is not NULL)
set @sql = @sql + ' where ' + @WhereCondition
if(@GroupBy <>'' and @GroupBy is not null)
set @sql = @sql + ' group by ' + @GroupBy
--处理页数超出范围情况
if @PageIndex<=0
Set @PageIndex = 1
if @PageIndex>@PageCount
Set @PageIndex = @PageCount
--处理开始点和结束点
Declare @StartRecord int
Declare @EndRecord int
set @StartRecord = (@PageIndex-1)*@PageSize + 1
set @EndRecord = @StartRecord + @PageSize - 1
--继续合成sql语句
SET @TableName='rowtable';
set @Sql = @Sql + ') as temptable where rowId between ' + Convert(varchar(50),@StartRecord) + ' and ' + Convert(varchar(50),@EndRecord)
Exec(@Sql)
---------------------------------------------------
If @@Error <> 0
Begin
-- RollBack Tran
Return -1
End
Else
Begin
--Commit Tran
Return @RecordCount ---返回记录总数
End
end