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

    set ANSI_NULLS ON
    set QUOTED_IDENTIFIER ON
    go




    -- =============================================
    -- Author: ***
    -- Create date: 2014-03-27 20:00
    -- Description: 採用最新的 row_number() over 技术高效分页方法
    -- =============================================
    ALTER PROCEDURE [dbo].[P_Public_Paging]
    @TableName Nvarchar(4000), --要显示的表、视图、或是SQL语句
    @FieldName nvarchar(4000) = '*', --要显示的字段列表,全部字段是* 大视图最好不要用*
    @PageSize int, --每页显示的记录个数(每页条数小于1则修正成10)
    @PageIndex int=1, --要显示那一页的记录(当前页小于1或自己主动修正为1)
    @Where  nvarchar(2000) = '1=1', --查询条件,不需where
    @OrderBy nvarchar(2000), --排序字段,最好是索引字段
    @PageCount int = 1 output, --返回分页后的总页数
    @RecordCount int =0 output --返回查询到的记录数
    AS
    BEGIN
    Declare @SelectSql nvarchar(4000) --构造Sql查询词句
    if @PageSize < 1 set @PageSize = 10--假设小每页大小小于1则修正成10
    set @SelectSql = ' select @RecordCount = count(0) from ' + @TableName + ' where ' + @Where
    exec sp_executesql @SelectSql ,N'@RecordCount int out ',@RecordCount out
    --计算@PageCount的值
    if @RecordCount <= @PageSize
    set @PageCount = 1
    else if @RecordCount % @PageSize = 0
    set @PageCount = (@RecordCount / @PageSize )
    else
    set @PageCount = (@RecordCount / @PageSize ) + 1
    --检查@PageIndex的值
    if @PageIndex> @PageCount
    set @PageIndex= @PageCount
    if @PageIndex < 1
    set @PageIndex = 1
    set @SelectSql = 'select '+@FieldName +'from (' +
    'select row_number() over (order by ' + @OrderBy + ')  RowID ,' + @FieldName +
    ' from ' + @TableName + ' where ' + @Where +
    ') a where a.RowID > ' + cast((@PageIndex -1) * @pageSize as varchar(128)) +
    ' and a.RowID <= ' + cast(@PageIndex * @pageSize as varchar(128))
    exec sp_executesql @SelectSql
    select @PageCount,@RecordCount
    END



    版权声明:本文博客原创文章。博客,未经同意,不得转载。

  • 相关阅读:
    leetcode--Populating Next Right Pointers in Each Node II
    leetcode—Populating Next Right Pointers in Each Node
    Pascal's Triangle II
    leetcode—pascal triangle
    leetcode—triangle
    October 23rd, 2017 Week 43rd Monday
    October 22nd, 2017 Week 43rd Sunday
    October 21st 2017 Week 42nd Saturday
    October 20th 2017 Week 42nd Friday
    October 19th 2017 Week 42nd Thursday
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/4690734.html
Copyright © 2011-2022 走看看