SQL Server使用row_number分页的实现方法

这篇文章主要为大家详细介绍了SQL Server使用row_number分页的实现方法,具有一定的参考价值,感兴趣的朋友可以参考一下

本文为大家分享了SQL Server使用row_number分页的实现方法,供大家参考,具体内容如下

1、首先是

select ROW_NUMBER() over(order by id asc) as 'rowNumber', * from table1

生成带序号的集合

2、再查询该集合的 第 1 到第 5条数据

?

1

2

3

select * from

(select ROW_NUMBER() over(order by id asc) as 'rowNumber', * from table1) as temp

where rowNumber between 1 and 5

完整的Sql语句

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

declare @pagesize int; declare @pageindex int; set @pagesize = 3

set @pageindex = 1; –第一页

select * from (select ROW_NUMBER() over(order by id asc) as 'rowNumber', * from table1) as temp where rowNumber between (((@pageindex-1)*@pagesize)+1) and (@pageindex*@pagesize)

set @pageindex = 2; –第二页

select * from (select ROW_NUMBER() over(order by id asc) as 'rowNumber', * from table1) as temp where rowNumber between (((@pageindex-1)*@pagesize)+1) and (@pageindex*@pagesize)

set @pageindex = 3; –第三页

select * from (select ROW_NUMBER() over(order by id asc) as 'rowNumber', * from table1) as temp where rowNumber between (((@pageindex-1)*@pagesize)+1) and (@pageindex*@pagesize)

set @pageindex = 4;–第四页

select * from (select ROW_NUMBER() over(order by id asc) as 'rowNumber', * from table1) as temp where rowNumber between (((@pageindex-1)*@pagesize)+1) and (@pageindex*@pagesize)

下面我们来写个存储过程分页

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

Alter Procedure PagePager

@TableName varchar(80),

@File varchar(1000),—

@Where varchar(500),—带and连接

@OrderFile varchar(100), — 排序字段

@OrderType varchar(10),–asc:顺序,desc:倒序

@PageSize varchar(10), —

@PageIndex varchar(10) —

as

if(ISNULL(@OrderFile, '') = '')

begin

set @OrderFile = 'ID';

end

if(ISNULL(@OrderType,'') = '')

begin

set @OrderType = 'asc'

end

if(ISNULL(@File,'') = '')

begin

set @File = '*'

end

declare @select varchar(8000)

set @select = ' select ' + @File + ' from ( select *,ROW_NUMBER() over(order by ' + @OrderFile + ' '+ @OrderType + ') as ''rowNumber'' from ' + @TableName + ' where 1=1 ' + @Where + ' ) temp where rowNumber between (((' + @PageIndex + ' – 1) * ' + @PageSize + ')+1) and (' + @PageIndex + '*'+ @PageSize+')'

exec(@select)

以上就是本文的全部内容,希望对大家学习row_number分页有所帮助。

版权声明:本文(即:原文链接:https://www.qin1qin.com/catagory/26424/)内容由互联网用户自发投稿贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 630367839@qq.com 举报,一经查实,本站将立刻删除。

(0)
上一篇 2022-09-27 8:25:51
下一篇 2022-09-27 8:25:57

软件定制开发公司

相关阅读

发表回复

登录后才能评论
通知:禁止投稿所有关于虚拟货币,币圈类相关文章,发现立即永久封锁账户ID!