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

    ALTER  PROCEDURE [dbo].[NTP_Page] 
      @IndexField varchar(50)='id',
      @AllFields varchar(1000)='*', --需要返回的列 
      @TablesAndWhere varchar(1000)='', -- 表名和条件,from后面的,不要from,要一条where
      @OrderFields varchar(255)='',-- 排序的字段名
      @PageSize int = 10, -- 页尺寸
      @PageIndex int = 1, -- 页码
      @RecordCount int output,
      @PageCount int output
    AS
    if @PageSize < 1
      set @PageSize = 10
      declare @strSQL nvarchar(4000) -- 主语句
      set @strSQL = 'select @RecordCount=count('+ @IndexField +') from '+ @TablesAndWhere
      exec sp_executesql @strSQL,N'@RecordCount int output',@RecordCount out
      if @RecordCount % @PageSize = 0
        set @PageCount = @RecordCount/@PageSize
      else
        set @PageCount = @RecordCount/@PageSize+1
      if(@PageIndex > @PageCount)
        set @PageIndex = @PageCount
      if @PageIndex < 1
        set @PageIndex = 1
      if @PageIndex = 1
        set @strSQL='select top ' + CAST(@PageSize as nvarchar) + ' ' + @AllFields + ' from '+ @TablesAndWhere + ' ' + @OrderFields
      else
        begin
          declare @start int
          set @start = (@PageIndex - 1) * @PageSize
          set @strSQL= 'select top ' + CAST(@PageSize as nvarchar) + ' ' +  @AllFields  + ' from ' +  @TablesAndWhere + ' and '+ @IndexField  + ' not in (select top ' + CAST(@start as nvarchar) + ' ' + @IndexField + ' from ' + @TablesAndWhere + ' ' + @OrderFields +') '+ @OrderFields
        end
        print @strSQL
        exec sp_executesql @strSQL
    将来的你,一定会感谢现在努力的自己!
  • 相关阅读:
    【bzoj2500】幸福的道路 树形dp+单调队列
    【ARC069F】Flags 2-sat+线段树优化建图+二分
    【bzoj2437】[Noi2011]兔兔与蛋蛋 二分图最大匹配+博弈论
    剑指offer——树的子结构
    剑指offer——反转链表
    腾讯算法岗面试算法题——计数排序
    作业帮面试题
    剑指offer——重建二叉树
    剑指offer——二维数组中的查找
    删除链表中重复的结点
  • 原文地址:https://www.cnblogs.com/GreatPerson/p/8060644.html
Copyright © 2011-2022 走看看