zoukankan      html  css  js  c++  java
  • SQL大语句——实现分页,select top后面跟变量出错

    之前想实现分页功能,在网上看了下,要实现分页读取而不是分页预览,一个较好的方法是写存储过程,有一个感觉可以,不过没有试验:

    在存储过程中加入一个小算法,直接输入参数(页数)读取比较划算,存储过程如下C#:
    create procedure class_c
    @x int
    as
    select classId,ClassName,EntranceDate,Remark from (
    --按scgrade降序排列,并按row_number() 分组
    select row_number() over (order by classId ASC) as num,*from Class)
    --加入算法,动态获取X的范围
    as n where num between @x*5-4 and @x*5

    然后又看到一篇文章,写的不错:http://www.williamlong.info/info/archives/241.html

    上面的方法有通用的,我主要是学习了一下上面较为简单又较好的语句,并仿照写了一个分页的存储过程:
    CREATE PROCEDURE proc_Paging
     @pageSize int,
     @currentPage int
    AS
    BEGIN
     SET NOCOUNT ON;
        select top @pageSize * from dbo.tbTestWellLogInfo
        where num>
        (select MAX(num) from
        (select top((@currentPage-1)*@pageSize) num from dbo.tbTestWellLogInfo order by num)as T
        )
        order by num
    END
    GO

    但是报错,说' select top @pageSize * from'中的@pageSize有语法错误,就重新采用了网上的拼接字符串方法,虽然成功执行了,但还是不很理解为什么那样修改就行:

    CREATE PROCEDURE proc_Paging
     @pageSize int,
     @currentPage int
    AS
    BEGIN
     SET NOCOUNT ON;
     declare @str varchar(1000)
        select @str = ''
        select @str='select top'+ @pageSize+' * from dbo.tbTestWellLogInfo
        where num>
        (select MAX(num) from
        (select top(('+@currentPage+'-1)*'+@pageSize+') num from dbo.tbTestWellLogInfo order by num)as T
        )
        order by num'
        exec(@str)
    END
    GO

    但是这样做虽然可以执行成功生成存储过程,但是执行一下,输入参数会发现有错误。再次修改原来语句,发现需要将变量@pageSize括起来:

    CREATE PROCEDURE proc_Paging
     @pageSize int,
     @currentPage int
    AS
    BEGIN
     SET NOCOUNT ON;
        select top (@pageSize) * from dbo.tbTestWellLogInfo
        where num>
        (select MAX(num) from
        (select top((@currentPage-1)*@pageSize) num from dbo.tbTestWellLogInfo order by num)as T
        )
        order by num
    END
    GO

    这样终于可以执行成功了,但是执行,输入参数,发现第一页的数据不能读出来,因为currentPage=1时,select max(num) from null 为null。最后附上正确语句:

    ALTER PROCEDURE proc_Paging
     @pageSize int,
     @currentPage int
    AS
    BEGIN
     SET NOCOUNT ON;
     if(@currentPage=1)select top (@pageSize) * from dbo.tbTestWellLogInfo
     else begin
        select top (@pageSize) * from dbo.tbTestWellLogInfo
        where num>
        (select MAX(num) from
        (select top((@currentPage-1)*@pageSize) num from dbo.tbTestWellLogInfo order by num)as T
        )
        order by num
        end
    END
    GO

  • 相关阅读:
    [Swift通天遁地]三、手势与图表-(9)制作五彩缤纷的气泡图表
    hdu2289 Cup(二分)
    Makefile学习(三)[第二版]
    CABasicAnimation 基本动画
    iOS_20_微博自己定义可动画切换的导航控制器
    yispider 开源小说採集器 (来源http://git.oschina.net/yispider/yispider 我的改动版由于他的我无法跑)
    谈谈C++私有继承
    深入struts2.0(七)--ActionInvocation接口以及3DefaultActionInvocation类
    STL 之 list源码自行实现(iterator)
    二分lower_bound()与upper_bound()的运用
  • 原文地址:https://www.cnblogs.com/denghuachengle/p/3478951.html
Copyright © 2011-2022 走看看