/*
函数名称: GetRecordFromPage
函数功能: 获取指定页的数据
参数说明: @tblName 包含数据的表名
@fldName 关键字段名
@PageSize 每页记录数
@PageIndex 要获取的页码
@OrderType 排序类型, 0 - 升序, 1 - 降序
@strWhere 查询条件 (注意: 不要加 where)
*/
CREATE PROCEDURE GetRecordFromPage
@tblName VARCHAR(255), -- 表名
@fldName VARCHAR(255), -- 字段名
@PageSize INT = 10, -- 页尺寸
@PageIndex INT = 1, -- 页码
@OrderType bit = 0, -- 设置排序类型, 非 0 值则降序
@strWhere VARCHAR(2000) = '' -- 查询条件 (注意: 不要加 where)
AS
DECLARE @strSQL VARCHAR(6000) -- 主语句
DECLARE @strTmp VARCHAR(1000) -- 临时变量
DECLARE @strOrder VARCHAR(500) -- 排序类型
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 = 1
BEGIN
SET @strTmp = ''
IF @strWhere != ''
SET @strTmp = ' where (' + @strWhere + ')'
SET @strSQL = 'select top ' + str(@PageSize) + ' * from ['
+ @tblName + ']' + @strTmp + ' ' + @strOrder
END
EXEC (@strSQL)
GO
//SQL/827