zoukankan      html  css  js  c++  java
  • Sql分页两种常用算法

      今天花了两个小时,写了两种分页的算法。

    --not in删选法,这种方法查询某个表中前面的数据效率高
    create procedure Page_proc
    (
    @pageSize int, --页数,
    @pageIndex int,--页码
    @tableName varchar(50),--表名
    @mast varchar(50)--表的主键名
    )
    as
    begin
     declare @arg int 
     set @arg=@pageSize*(@pageIndex-1)
     
     --使用动态Sql
     declare @strSql varchar(1000)
     set @strSql='select top('+cast(@pageSize as varchar(20))+') * from '+@tableName
     +' where '+@mast+' not in(select top('+cast(@arg as varchar(20))+') '+@mast+' from '+@tableName+')'
     print @strSql
     exec(@strSql)
    end

    --正序倒序法,这种方法查询某个表中后面的数据效率高

    create proc FenYe
    @tableName varchar(50),--表名
    @mast varchar(50),--表的主键名
    @pageIndex int,--页码
    @pageCount int--页数
    as
    begin
        --求出表的总行数,由于是动态Sql给@RowCount赋值,所以需要用到sp_executesql
        declare @RowCount int
        declare @countSql nvarchar(200)
        set @countSql='select @innerCount=count(*) from '+@tableName

        exec sp_executesql @countSql,N'@innerCount int output',@RowCount output
        --print @RowCount
        --求出子查询要查的行数
        declare @Count int
        set @Count=@RowCount-(@pageIndex-1)*@pageCount
        
        --如果查询条件不符合则结束此存储过程
        if(@Count<0)
        return ;
        --使用动态Sql
        declare @strSql varchar(1000)
        set @strSql='select top '+cast(@pageCount as varchar(20))+' * from '+'(select top '+
        cast(@Count as varchar(20))+' * from '+cast(@tableName as varchar(50))+' order by '
        +cast(@mast as varchar(50))+' desc) as temp order by '+cast(@mast as varchar(50))

        print @strSql
        exec(@strSql
    end

    这两种是最常用的,第一次发技术随笔,不足之处请大家了解。

     使用正序倒叙法查询表前面的数据成功例子:

    select * from (select top 10 * from (select top 12 * from A0002 order by ID asc) as temp order by ID desc) as tt order by ID

     使用正序倒叙法查询表前面的数据失败例子:

    select top 10 * from (select top 12 * from A0002 order by ID asc) as temp order by ID asc
     
  • 相关阅读:
    Gmail、还有人需要吗?
    Google 打不开
    不能忽视的Doctype
    ASP.NET2.0中用ICallbackEventHandler实现客户端与服务器端异步交互
    DataGrid常用小技巧
    ASP.NET程序安全性(三) 表单提交、过滤用户输入
    Objection!!!
    编写3dmax插件需要注意的几个问题
    又一个IGame的bug
    VC2010中的C++0x特性 Part 1:Lambdas,auto, static_assert
  • 原文地址:https://www.cnblogs.com/mxw09/p/1610635.html
Copyright © 2011-2022 走看看