zoukankan      html  css  js  c++  java
  • SQLServer分页

    一、创建测试表

    CREATE TABLE [dbo].[Student](
        [id] [int] NOT NULL,
        [name] [nvarchar](50) NULL,
        [age] [int] NULL)

    二、创建测试数据

    declare @i int
    set @i=1
    while(@i<10000)
    begin
        insert into Student select @i,left(newid(),7),@i+12
        set @i += 1
    end

    三、测试

    1、使用top关键字

    top关键字表示跳过多少条取多少条

    declare @pageCount int  --每页条数
    declare @pageNo int  --页码
    declare @startIndex int --跳过的条数
    set @pageCount=10
    set @pageNo=3
    set @startIndex=(@pageCount*(@pageNo-1)) 
    select top(@pageCount) * from Student
    where ID not in
    (
      select top (@startIndex) ID from Student order by id 
    ) order by ID

     测试结果:

    2、使用row_number()函数

    declare @pageCount int  --页数
    declare @pageNo int  --页码
    set @pageCount=10
    set @pageNo=3
    --写法1:使用between and 
    select t.row,* from 
    (
       select ROW_NUMBER() over(order by ID asc) as row,* from Student
    ) t where t.row between (@pageNo-1)*@pageCount+1 and @pageCount*@pageNo
    --写法2:使用 “>”运算符
     select top (@pageCount) * from 
    (
       select ROW_NUMBER() over(order by ID asc) as row,* from Student
    ) t where t.row >(@pageNo-1)*@pageCount
    --写法3:使用and运算符 
    select top (@pageCount) * from 
    (
       select ROW_NUMBER() over(order by ID asc) as row,* from Student
    ) t where t.row >(@pageNo-1)*@pageCount and t.row<(@pageNo)*@pageCount+1

    四、总结

    ROW_NUMBER()只支持sql2005及以上版本,top有更好的可移植性,能同时适用于sql2000及以上版本、access。

  • 相关阅读:
    C++学习004-Go To 语句使用
    C++学习003-#define 自定义宏
    C++学习002-C++代码中插入汇编语句
    C++学习001-注释
    Qt 加载Leap motion 手势识别软件 二次开发 hello world
    C++知识点 内存占用问题
    虚拟现实-VR-UE4-编译源代码后,无法运行
    Loadrunner|录制脚本时出现乱码的解决方式
    2月14日学习内容
    构建之法读后感(三)
  • 原文地址:https://www.cnblogs.com/dotnet261010/p/10784315.html
Copyright © 2011-2022 走看看