分页
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER PROCEDURE [dbo].[sp_Pagination2005]
(
@tblName varchar(255), -- 表名
@fields varchar(1000) = '*', -- 需要返回的列
@sortField varchar(255)='', -- 排序的字段名, max(字段)或min(字段)字段不重复
@pageSize int = 10, -- 页尺寸
@pageIndex int = 1, -- 页码
@sortDescending bit = 0, -- 是否降序
@strWhere varchar(1500) = '', -- 查询条件 (注意: 不要加 WHERE)
@totalRecords int=0 output -- 总记录数
)
AS
SET NOCOUNT ON;
DECLARE @strSQL nvarchar(4000) -- 主语句
DECLARE @strOrder varchar(400) -- 排序类型
--IF @doCount != 0
-- BEGIN
IF @strWhere !=''
SET @strSQL = 'SELECT @cnt=count(*) FROM [' + @tblName + '] WHERE '+@strWhere
ELSE
SET @strSQL = 'SELECT @cnt=count(*) FROM [' + @tblName + ']'
EXEC sp_executesql @strSQL,N'@cnt int output',@totalRecords output
--SELECT @totalRecords as N'@totalRecords'
-- END
--ELSE
-- BEGIN
IF @sortDescending != 0
BEGIN
SET @strOrder = ' ORDER BY [' + @sortField +'] desc'
--如果@sortDescending不是0,就执行降序,这句很重要!
END
ELSE
BEGIN
SET @strOrder = ' ORDER BY [' + @sortField +'] asc'
END
IF @pageIndex = 1
BEGIN
IF @strWhere != ''
SET @strSQL = 'SELECT TOP ' + str(@pageSize) +' '+@fields+ ' FROM [' + @tblName + '] WHERE ' + @strWhere + ' ' + @strOrder
ELSE
SET @strSQL = 'SELECT TOP ' + str(@pageSize) +' '+@fields+ ' FROM ['+ @tblName + '] '+ @strOrder
--如果是第一页就执行以上代码,这样会加快执行速度
END
ELSE
BEGIN
--以下代码赋予了@strSQL以真正执行的SQL代码
SET @strSQL = 'SELECT TOP ' + str(@pageSize) +' '+@fields+' FROM'
+'(SELECT '+@fields+',ROW_NUMBER() OVER ('+@strOrder+') AS RowNo FROM [' + @tblName + ']) AS T '
+'WHERE RowNo >'+str((@pageIndex-1)*@pageSize)
IF @strWhere != ''
SET @strSQL = 'SELECT TOP ' + str(@pageSize) +' '+@fields+' FROM'
+'(SELECT '+@fields+',ROW_NUMBER() OVER ('+@strOrder+') AS RowNo FROM [' + @tblName + '] WHERE ' + @strWhere + ' ) AS T '
+'WHERE RowNo >'+str((@pageIndex-1)*@pageSize)
END
-- END
exec (@strSQL)
SET NOCOUNT OFF;
posted on 2010-05-27 17:09 jianshaohui 阅读(98) 评论(0) 编辑 收藏 举报