sql分页查询语句

1.调用的存储过程

Create PROCEDURE [db_datareader].[SP_Test]
@ActionType NVARCHAR(40) = NULL,
@SqlWhere nvarchar(2000)=null,
@PageSize int = NULL,
@PageIndex int = NULL,
@RecordCount bigint=null OUTPUT

AS
BEGIN
if(@ActionType='Process1')
	BEGIN
     	exec [spG_Test] @tblName='VM_Test,--表名或视图
		@fldName ='*',--显示的字段
		@fldSort='DataAreaId',
		@strCondition=@SqlWhere,
		@pageSize=@PageSize,
		@pageIndex=@PageIndex, 
		@totalRecord =@RecordCount output
	END
END

2.分页存储过程

create Procedure [db_datareader].[spG_Test]
@tblName nvarchar(300),                --表名
@fldName nvarchar(1000) = '*',          --字段名(全部字段为*)from 500 to 1000
@fldSort nvarchar(500),                --排序字段(必须!支持多字段)
@strCondition nvarchar(2000) = Null,    --条件语句(不用加where)
@pageSize int,                         --每页多少条记录
@pageIndex int = 1 ,                   --指定当前为第几页
@totalRecord int=0 output,             --返回总行数
@TotalPage int =1 output               --返回总页数 
as
begin

    Begin Tran --开始事务
	SET NOCOUNT on 
	declare @timediff datetime --耗时测试时间差 
	select @timediff=getdate() 
    Declare @sql nvarchar(4000);
     --计算总记录数
     if (@strCondition='' or @strCondition is NULL)
         set @sql = 'select @totalRecord = count(*) from ' + @tblName
     else
     begin		
         set @sql = 'select @totalRecord = count(*) from  (select '+@fldName+'  from ' + @tblName + ' where ' + @strCondition+')'+' as t'
		 print 'success--'+@sql
	 end
     EXEC sp_executesql @sql,N'@totalRecord int OUTPUT',@totalRecord OUTPUT--计算总记录数        
     --计算总页数
     select @TotalPage=CEILING((@totalRecord+0.0)/@pageSize)
		if (@strCondition='' or @strCondition is NULL)
			set @sql = 'Select * FROM ( select  ROW_NUMBER() Over(order by ' + @fldSort + ') as rowId,' + @fldName + ' from ' + @tblName 
		else
			set @sql = 'Select * FROM (select  ROW_NUMBER() Over(order by ' + @fldSort + ') as rowId,' + @fldName + ' from ' + @tblName + ' where ' + @strCondition    
     --处理页数超出范围情况
     if @pageIndex<=0 
         Set @pageIndex = 1
     if @pageIndex>@TotalPage
         Set @pageIndex = @TotalPage
      --处理开始点和结束点
     Declare @StartRecord int
     Declare @EndRecord int
     set @StartRecord = (@pageIndex-1)*@pageSize + 1
     set @EndRecord = @StartRecord + @pageSize - 1
     --继续合成sql语句
	 set @sql = @sql + ') as t where rowId between ' + Convert(varchar(50),@StartRecord) + ' and ' +   Convert(varchar(50),@EndRecord)
	 print @sql
     exec sp_executesql @sql
     ---------------------------------------------------
     If @@Error <> 0
       Begin
         RollBack Tran
         Return -1
       End
      Else
       Begin
         Commit Tran
         print @totalRecord 
         print @TotalPage
       End    
end
SET NOCOUNT OFF 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值