在圈子里的找了一个分页存储过程,
set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go CREATE PROCEDURE [dbo].[Proc_Page] ( @TableName varchar(50), --表名或视图 @ReFieldsStr varchar(200) = '*', --字段名(全部字段为*) @OrderFiled varchar(200), --排序字段(必须!支持多字段不用加order by) @OrderType int = 0, -- 设置排序类型, 非0 值则降序 @WhereString varchar(500) =N'', --条件语句(不用加where) @PageSize int, --每页多少条记录 @PageIndex int = 1 , --指定当前为第几页 @TotalRecord int output --返回总记录数 ) AS BEGIN --处理开始点和结束点 Declare @StartRecord int; Declare @EndRecord int; Declare @TotalCountSql nvarchar(500); Declare @SqlString nvarchar(2000); set @StartRecord = (@PageIndex-1)*@PageSize + 1 set @EndRecord = @StartRecord + @PageSize - 1 SET @TotalCountSql= N'select @TotalRecord = count(*) from [' + @TableName+']';--总记录数语句 IF @OrderType!=0 --降序 BEGIN SET @SqlString = N'(select row_number() over (order by '+ @OrderFiled +' desc) as rowId,'+@ReFieldsStr+' from ['+ @TableName+']';--查询语句 END ELSE BEGIN SET @SqlString = N'(select row_number() over (order by '+ @OrderFiled +' asc) as rowId,'+@ReFieldsStr+' from ['+ @TableName+']';--查询语句 END -- IF (@WhereString! = '' or @WhereString!=null) BEGIN SET @TotalCountSql=@TotalCountSql + ' where '+ @WhereString; SET @SqlString =@SqlString+ ' where '+ @WhereString; END --第一次执行得到 --IF(@TotalRecord is null) -- BEGIN EXEC sp_executesql @totalCountSql,N'@TotalRecord int out',@TotalRecord output;--返回总记录数 -- END ----执行主语句 set @SqlString ='select * from ' + @SqlString + ') as t where rowId between ' + ltrim(str(@StartRecord)) + ' and ' + ltrim(str(@EndRecord)); Exec(@SqlString) END EXEC dbo.Proc_Page @TableName = 'Afagouinfo', -- varchar(50) @ReFieldsStr = 'diqu,flag', -- varchar(200) @OrderFiled = 'id', -- varchar(200) @OrderType = 0, -- int @WhereString = '', -- varchar(500) @PageSize = 10, -- int @PageIndex = 1, -- int @TotalRecord = 20 -- int