/*The store produce must need main ID,
It can get record of each page and the count of record,
You can get two ResultSet use by getMoreElement() in java*/
CREATE PROCEDURE GetPageRecordAndCount(
@tblName NVARCHAR(255), -- 表名
@id NVARCHAR(255), -- 主键ID
@fldName NVARCHAR(255), -- 字段名,用来排序
@PageSize int = 10, -- 页尺寸
@PageIndex int = 1, -- 页码
@OrderType bit = 0, -- 设置排序类型, 非 0 值则降序
@strWhere NVARCHAR(1000) = '' -- 查询条件 (注意: 不要加 where)
)AS
declare @strSQL NVARCHAR(1000) -- 主语句
declare @strTmp NVARCHAR(300) -- 临时变量
declare @strOrder NVARCHAR(400) -- 排序类型
if @OrderType != 0
begin
set @strTmp = 'NOT IN'
set @strOrder = ' order by [' + @fldName +'] desc'
end
else
begin
set @strTmp = 'NOT IN'
set @strOrder = ' order by [' + @fldName +'] asc'
end
--SELECT TOP 5 * FROM tb_productInfo WHERE productId NOT IN(SELECT TOP 5 productId FROM tb_productInfo ORDER BY productName) ORDER BY productName
set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
+ @tblName + '] where [' + @id + ']' + @strTmp + ' (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
+ @id + '] from [' + @tblName + ']' + @strOrder + ' )'
+ @strOrder
if @strWhere != ''
set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
+ @tblName + '] where [' + @id + ']' + @strTmp + ' (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
+ @id + '] from [' + @tblName + '] where (' + @strWhere + ') '
+ @strOrder + ') 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)
set @strSQL = 'select count(*) as Total from [' + @tblName + ']'
if @strWhere != ''
BEGIN
set @strSQL = 'select count(*) as Total from [' + @tblName + '] WHERE '+@strWhere
END
exec (@strSQL)