你一定见过这样的SQL语句
select top 5 * from (select top 15 * from tableNameorder by id asc) tableName order by id desc
或者类似用select top 方式的分页储存过程
SQL Server2005 中row_number函数的诞生,在处理分页上简化了很多语句
row_number函数的用途是非常广泛,这个函数的功能是为查询出来的每一行记录生成一个序号。row_number函数的用法如下面的SQL语句所示:
没有使用row_number函数
SELECT * FROM tableName
使用row_number函数
select row_number() over(order by id) as row_number,* from tableName
其中row_number列是由row_number函数生成的序号列。在使用row_number函数是要使用over子句选择对某一列进行排序,然后才能生成序号。
使用row_number 函数返回2—4条记录
with tableName_row
as
(
select row_number() over(order by id) as row_number,* from tableName
)
select * from tableName_row where row_number>1 and row_number < 5 order by id
下面是一个分页的存储过程使用row_number 函数
代码
alter PROCEDURE [dbo].[p_ExecPagedBySqlCmd]
(
@from_where nvarchar(2000),--传入的查询条件(from tableName where id=1)
@returncols nvarchar(1000),--需要返回的字段名称
@pageorder varchar(200), --排序的字段 ex name desc'
@PageIndex int, --页码
@PageSize int=20, --每页的数量
@returntotalsize bit=1 --是否返回记录的总数
)
AS
BEGIN
SET NOCOUNT ON;
declare @dysql nvarchar(4000)
declare @totalsize as int
begin
if @returntotalsize=1
BEGIN
set @dysql='select @totalsize=count(1) '+@from_where
set @dysql=@dysql+';select @totalsize as totalsize,* from (select ROW_NUMBER() OVER(ORDER BY '
+ @pageorder + ') AS rownum,' + @returncols ++' '+@from_where
+ ' ) as tb where rownum BETWEEN (@PageIndex-1)*@PageSize+1 AND @PageIndex*@PageSize order by ' + @pageorder
END
ELSE
BEGIN
set @dysql='select * from (select ROW_NUMBER() OVER(ORDER BY '
+ @pageorder + ') AS rownum,' + @returncols ++' '+@from_where
+ ' ) as tb where rownum BETWEEN (@PageIndex-1)*@PageSize+1 AND @PageIndex*@PageSize order by ' + @pageorder
END
execute sp_executesql @dysql,N'@totalsize int,@PageIndex int,@PageSize int',@totalsize,@PageIndex,@PageSize
return
end
END
欢迎大家指导!