MSSQL通用分页存储过程

本文介绍了一个使用SQL Server存储过程实现动态分页查询的方法,包括动态SQL的构造和执行,适用于不同表结构和查询条件的场景。

 

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


ALTER        PROCEDURE [dbo].[GetDataSet] 
@TableList Varchar(200)='*',
@TableName Varchar(300),
@SelectWhere Varchar(1000)='',
@SelectOrderId Varchar(200),
@SelectOrder Varchar(200)='',
@intPageNo int=1--页号
@intPageSize int=10 --每页显示数
as
begin
    
set nocount on--关闭计数
    declare @RecordCount int  --总记录数(存储过程输出参数)
    declare @TmpSelect      NVarchar(2000)  
    
declare @Tmp     NVarchar(600)  

    
if @SelectWhere=''
        
begin
            
set @TmpSelect = 'select @RecordCount = count(*) from '+@TableName
        
end
    
else
        
begin
            
set @TmpSelect = 'select @RecordCount = count(*) from '+@TableName +' where '+@SelectWhere
        
end
    
execute sp_executesql  @TmpSelect,    --执行上面的sql语句
    N'@RecordCount int OUTPUT' ,  --执行输出数据的sql语句,output出总记录数
    @RecordCount  OUTPUT
    
--if (@RecordCount = 0)    --如果没有,则返回零
               --return 0
    /*判断页数是否正确*/
      
if (@intPageNo - 1* @intPageSize > @RecordCount   --页号大于总页数,返回错误
        return (-1)
    
--set nocount off--打开计数

    
if @SelectWhere != '' 
        
begin
            
set @TmpSelect = 'select top '+str(@intPageSize)+' '+@TableList+' , '''+str(@RecordCount)+''' as Count from '+@TableName+' where '+@SelectOrderId+' not in(select top '+str((@intPageNo-1)*@intPageSize)+' '+@SelectOrderId+' from '+@TableName+' where 1=1 and '+@SelectWhere +' '+@SelectOrder+') and '+@SelectWhere +' '+@SelectOrder
        
end
    
else
        
begin
            
set @TmpSelect = 'select top '+str(@intPageSize)+' '+@TableList+' , '''+str(@RecordCount)+''' as Count from '+@TableName+' where '+@SelectOrderId+' not in(select top '+str((@intPageNo-1)*@intPageSize)+' '+@SelectOrderId+' from '+@TableName+' '+@SelectOrder+''+@SelectOrder
        
end
    
execute sp_executesql @TmpSelect
    
return(@@rowcount)
end

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值