SQL Server两种分页的存储过程使用介绍
由于现在很多的企业招聘的笔试都会让来招聘的写一个分页的存储过程,有的企业甚至要求应聘者用两种方式实现分页,如果没有在实际项目中使用过分页,那么很多的应聘者都会出现一定的问题,下面介绍两种分页的方法。 一、 以学生表为例,在数据库中有一个student表,字段有studentno, ,loginpwd, studentname,sex,classid,phone,address,borndate,email,isdel 要求:查询学生的信息,每页显示5条记录 二、第一种方式分页:利用子查询 not in 例如: 第一页 select top 5 * from student 第二页: 查询前10条中不在前5条的记录,那么就是6-10,也就是第二页 select top 5 * from student where studentno not in(select top 10 studentno from student) 同理可以得到第三页、、、、、、、 这种方式相信大家都能明白,这种分页的存储过程写法就不多做介绍,重点介绍下面那种分页方法。 三、第二种方式分页:利用row_number()这个自带的函数 因为自05之后,提供一个专门用于分页的函数,那就是row_number()这个函数,分页的基本语法:row_number() over(排序字段):可以根据指定的字段排序,对排序之后的结果集的每一行添加一个不间断的行号,相当于连续的id值一样, 例如sql语句:select row_number() over(order by studentno) id, * from student 那么结果集可以看到: 那么我们可以看到id值是连续的Mssq分页存储过程,所有接下来的存储过程写起来就比较简单了。 注意:我们必须为这个结果集命一个新名字,比如我们命名为temp,那么分页存储过程可以写出: if exists( select * from sysobjects where name='usp_getpagedata') drop proc usp_getpagedata --如果存在名字为usp_getpagedata的存储过程则删除 go create proc usp_getpagedata --创建名字usp_getpagedata存储过程 @topage int=0 output, --总页数 @pageindex int =1 , --默认显示第一页 @pagecount int =5 --默认每页的记录为5条 as select temp.studentno,temp.loginpwd,temp.studentname,temp.sex,temp.classid,temp.phone,temp.address,temp.borndate,temp.email,temp.isdel from (select row_number() over (order by studentno) id,* from student) temp where id>(@pageindex-1)*@pagecount and id<=@pageindex*@pagecount set @topage=ceiling((select count(*) from student)*1.0/@pagecount) --使用ceiling函数算出总页数 go 说明因为在实际的项目的开发中,经常要显示总页数给用户看的,所有这里的存储过程增加了一个topage参数,由于它是要输出给用户看的,所有参数类型定义为output,并用set进行赋值。 以上是对两种分页方法的介绍,如果有任何疑问或不懂的可以留言给我。 高明论坛: (编辑:重庆站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |