• 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 5 Studentno from Student)

    同理可以得到第三页、、、、、、、

    这种方式相信大家都能明白,这种分页的存储过程写法就不多做介绍,重点介绍下面那种分页方法。

     

    三、第二种方式分页:利用ROW_NUMBER()这个自带的函数

         因为自05之后,提供一个专门用于分页的函数,那就是ROW_NUMBER()这个函数,分页的基本语法:ROW_NUMBER() over(排序字段):可以根据指定的字段排序,对排序之后的结果集的每一行添加一个不间断的行号,相当于连续的id值一样,

    例如sql语句:select ROW_NUMBER() over(order by studentno) id, * from Student 那么结果集可以看到:

        

    那么我们可以看到id值是连续的,所有接下来的存储过程写起来就比较简单了。

    注意:我们必须为这个结果集命一个新名字,比如我们命名为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进行赋值。

        以上是对两种分页方法的介绍,如果有任何疑问或不懂的可以留言给我。

  • 相关阅读:
    常见cout格式输出
    P3332 [ZJOI2013]K大数查询
    pdb
    OS
    ubuntu su failure when password was right
    【opencv安裝】ubuntu16 opencv安装+测试
    shell脚本读取文件+读取命令行参数+读取标准输入+变量赋值+输出到文件
    xshell上传下载文件
    【sed / awk脚本编写】
    shell正则式解析身份证和手机号
  • 原文地址:https://www.cnblogs.com/xiaoyuanding/p/3855661.html
Copyright © 2020-2023  润新知