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