CREATE PROC GetRecordFromPage
@tableName varchar(255), -- 表名
@fieldName varchar(255), -- 字段名
@PageSize int = 10, -- 每页显示多少条
@PageIndex int = 1, -- 第几页
@OrderType bit = 0, -- 设置排序类型, 非0 值则降序
@IsCount bit = 0, -- 为0返回记录总数, 非0 值则返回数据集
@strWhere varchar(2000) = '' -- 查询条件 不要where
AS
declare @strSQL varchar(5000) -- 主语句(变量)
declare @strTemp varchar(1000) -- 临时条件(变量)
declare @strOrder varchar(500) -- 排序字段
if @OrderType != 0
begin
set @strTemp = '<(select min'
set @strOrder = ' order by [' + @fieldName + '] desc'
end
else
begin
set @strTemp = '>(select max'
set @strOrder = ' order by [' + @fieldName +'] asc'
end
set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
+ @tableName + '] where [' + @fieldName + ']' + @strTemp + '(['
+ @fieldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
+ @fieldName + '] from [' + @tableName + ']' + @strOrder + ') as tblTmp)'
+ @strOrder
if @strWhere != ''
set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
+ @tableName + '] where [' + @fieldName + ']' + @strTemp + '(['
+ @fieldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
+ @fieldName + '] from [' + @tableName + '] where ' + @strWhere + ' '
+ @strOrder + ') as tblTmp) and ' + @strWhere + ' ' + @strOrder
if @PageIndex = 1
begin
set @strTemp = ''
if @strWhere != ''
set @strTemp = ' where (' + @strWhere + ')'
set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
+ @tableName + ']' + @strTemp + ' ' + @strOrder
end
if @IsCount != 0
set @strSQL = 'select count(' + @fieldName + ') as Total from [' + @tableName + ']'
exec (@strSQL)