zoukankan      html  css  js  c++  java
  • 通用SQL分页过程

    set ANSI_NULLS ON
    set QUOTED_IDENTIFIER ON
    go





    ALTER PROCEDURE [dbo].[sp_Select_Page]
    (
        @pageSize int ,                --一页要显示的行数  
        @pageIndex int,                --第几页   参数
        @tabname nvarchar(100),     --对那张表
        @tdname nvarchar(200),        --需要那些字段
        @where nvarchar(2000),        --条件
        @order nvarchar(200),        --排序规则 例如  order by id,name
        @orderd nvarchar(200),        --反排序  例如  order by id desc,name desc
        @recount int=1 output,        --得到查询的总条数
        @pagsum int=1 output        --得到查询的总页数
    )
    AS
    BEGIN
        Declare @sql nvarchar(4000)   --变量
        Declare @sql1 nvarchar(4000)
        set @sql1='select @recount=count(*) from '+@tabname +' '+@where
        exec sp_executesql @sql1,N'@recount int out ',@recount out
        print @recount
        if(@recount%@pageSize)=0
        begin
            set @pagsum=@recount/@pageSize
        end
        else
        begin
            set @pagsum=@recount/@pageSize+1
        end
        print @pagsum
        if((@pageSize*@pageIndex)<@recount)
        begin
            set @sql='select '+ 'top '+str(@pageSize*@pageIndex)+'' +@tdname +' from ' +@tabname +' '+@where+' '+@order
            set @sql1='select '+ 'top '+str(@pageSize)+'' +@tdname +' from ('+@sql +') as a ' +@orderd
            set @sql='select '+ @tdname +' from (' +@sql1+') as b ' +@where+' '+@order
        end
        else
        begin
            set @sql='select '+ 'top '+str(@pageSize*@pageIndex)+'' +@tdname +' from ' +@tabname +' '+@where+' '+@order
            set @sql1='select '+ 'top '+str(@recount-@pageSize*(@pageIndex-1))+'' +@tdname +' from ('+@sql +') as a '+@orderd
            set @sql='select '+ @tdname +' from (' +@sql1+') as b ' +@where+' '+@order
        end
        print @sql
    print 3
        exec sp_executesql @sql
    END

  • 相关阅读:
    Python入门11 —— 基本数据类型的操作
    Win10安装7 —— 系统的优化
    Win10安装6 —— 系统的激活
    Win10安装5 —— 系统安装步骤
    Win10安装4 —— 通过BIOS进入PE
    Win10安装2 —— 版本的选择与下载
    Win10安装1 —— 引言与目录
    Win10安装3 —— U盘启动工具安装
    虚拟机 —— VMware Workstation15安装教程
    Python入门10 —— for循环
  • 原文地址:https://www.cnblogs.com/hznet/p/1805288.html
Copyright © 2011-2022 走看看