zoukankan      html  css  js  c++  java
  • 超级强大的 分页Sql存储过程

    CREATE PROCEDURE [dbo].[GetPage]
     @StrSelect varchar(max) = null,  --欲显示的列(多列用逗号分开),例如:id,name
        @StrFrom varchar(max) = null,  --表名称,或者是表连接字符串,多表连接例如:student as s inner join dwinfo as dw on s.dwbh=dw.bh
        @StrWhere varchar(max) = null,  --查询条件,null代表没有条件,单条件或者多条件,多条件例如:name='啊' and id=10
        @StrOrder varchar(max) = null,  --排序列(多个排序列用逗号分开),例如:id desc,name as
        @ItemCount bigint = 0 output,  --总记录数
        @PageSize int = 50,     --每页显示条数
     @PageIndex int = 1     --当前页

    AS
    BEGIN
        SET NOCOUNT ON;
        Declare @sql nvarchar(4000);
        Declare @totalRecord int;
        if (@StrWhere ='''' or @StrWhere='' or @StrWhere is NULL)
        set @sql = 'select @totalRecord = count(*) from ' + @StrFrom
        else
        set @sql = 'select @totalRecord = count(*) from ' + @StrFrom + ' where ' + @StrWhere
        EXEC sp_executesql @sql,N'@totalRecord int OUTPUT',@ItemCount OUTPUT
        declare @SqlQuery varchar(max)
    if(@PageIndex=1)
        begin
      if(@StrWhere is null)
      set @SqlQuery='select top '+convert(varchar,@PageSize)  + ' row_number() over(order by '+@StrOrder+' ) as RowNumber,'+@StrSelect+' from '+@StrFrom;
            else
      set @SqlQuery='select top '+convert(varchar,@PageSize) + ' row_number() over(order by '+@StrOrder+' ) as RowNumber,'+@StrSelect+' from '+@StrFrom+' where '+@StrWhere;
     end
    else
     begin
      if(@StrWhere is null)
      begin
       set @SqlQuery='with cte as (select row_number() over(order by '+@StrOrder+' ) as RowNumber,'+@StrSelect+' from '+@StrFrom+')select * from cte where RowNumber between '+
       convert(varchar,((@PageIndex-1)*@PageSize)+1)+' and '+
       convert(varchar,@PageIndex*@PageSize)
      end
      else
      begin
       set @SqlQuery='with cte as (select row_number() over(order by '+@StrOrder+' ) as RowNumber,'+@StrSelect+' from '+@StrFrom+' where '+@StrWhere+') select * from cte where RowNumber between '+
       convert(varchar,((@PageIndex-1)*@PageSize)+1)+' and '+
       convert(varchar,@PageIndex*@PageSize)
      end
     end
     print @SqlQuery
     exec (@SqlQuery)
    END

    insert into TBjhMovie values(newid(),'视频一','123','信息')

    select *from tbjhmovie


    declare @pageCount bigint ;
    exec [GetPage] 'movieName,movieMessage','[TBjhMovie]',null,'movieName desc',@pageCount,2,1
    select @pageCount

    ------------------------------------------此存储过程有单眼皮小猪 曹春辉 编写。--------------------------------

  • 相关阅读:
    CVE-2010-3333
    CVE-2010-2883
    谷歌不兼容showModalDialog()方法出现对话窗口解决方法
    asp.net中邮箱发送
    在c#中access2003和access2007连接字符串
    MVC连接Sql Server数据库出现的小问题
    使用360浏览器访问字体逆时针旋转90度的问题
    bootstrap与360浏览器不兼容问题
    委托的使用方法
    某集网将我的信息给了谁?还是不良卖家不想卖东西
  • 原文地址:https://www.cnblogs.com/nidakun/p/2601420.html
Copyright © 2011-2022 走看看