• sql 2005 分页存储过程


    set ANSI_NULLS ON
    set QUOTED_IDENTIFIER ON
    go







    -- [SelectBase] 1,1,'Users','username=''test'''
    ALTER procedure [dbo].[SelectBase]
    @PageIndex                    int,
    @PageSize                    int,
    @TableName       nvarchar(max),
    @Where                     nvarchar(max)=''

    as
    Declare @rowcount          int
    Declare @intStart          int
    Declare @intEnd         int

    Declare @SQl nvarchar(max), @WhereR nvarchar(max), @OrderBy nvarchar(max)
    set @rowcount=0
    set nocount on

    if @Where<>''
    begin
      
    set @Where=' and '+@Where
    end

    if CHARINDEX('order by'@Where)>0
    begin
        
    set @WhereR=substring(@Where1CHARINDEX('order by',@Where)-1)    --取得条件
        set @OrderBy=substring(@WhereCHARINDEX('order by',@Where), Len(@Where))    --取得排序方式(order by 字段 方式)
    end
    else
    begin
        
    set @WhereR=@Where
        
    declare @PKName nvarchar(50)
        
    if(len(@TableName)>50)
        
    begin
            
    Set @PKName='ID'
        
    end
        
    else
        
    begin
            
    select top 1 @PKName=[name] from syscolumns where id=object_id(@TableNameorder by colstat desc
        
    end
        
    set @OrderBy=' order by '+@PKName+' asc'
    end

    set @SQl='SELECT @rowcount=count(*) from '+cast(@TableName as nvarchar(3000))+' where 1=1 '+@WhereR
    exec sp_executeSql @SQl,N'@rowcount int output',@rowcount output

    if @PageIndex=0 and @PageSize=0    --不进行分页,查询所有数据列表
    begin
        
    set @SQl='SELECT * from '+cast(@TableName as nvarchar(3000))+' where 1=1 '+@Where
    end
    else    --进行分页查询数据列表
    begin
        
    set @intStart=(@PageIndex-1)*@PageSize+1;
        
    set @intEnd=@intStart+@PageSize-1

        
    set @SQl='select * from(select *,ROW_NUMBER() OVER('+cast(@OrderBy as nvarchar)+') as row from '
        
    set @SQl=@SQL+@TableName+' where 1=1 '+@WhereR+') as a where row between '+cast(@intStart as varchar)+' and '+cast(@intEnd as varchar)
    end
    --print @SQl
    exec sp_executeSql @SQl
    --select @rowcount
    return @rowcount

    --------------------------------------------
    --
    print @SQl
    --
    exec [SelectBase] 1,8,'SpaceContent','UserInfoID=45'

    set nocount off







    版权声明:本文原创发表于 博客园,作者为 路过秋天 本文欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则视为侵权。
    个人微信公众号
    创业QQ群:617713515
    Donation(扫码支持作者):支付宝:
    Donation(扫码支持作者):微信:
  • 相关阅读:
    Python 线程(三):Condition(条件变量)
    Python 线程(二):简单锁实现线程同步
    Python 线程(一):创建线程
    Python 正则表达式
    Python List 、 元组、字典操作
    Python 特殊函数(filter, map, reduce等)
    (一) log4cpp的安装
    (六) 字符和字符串
    (五) 使用DLL函数
    (四) 自定义函数
  • 原文地址:https://www.cnblogs.com/cyq1162/p/1545030.html
Copyright © 2020-2023  润新知