set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER PROCEDURE [dbo].[GetPageList]
@Fields VARCHAR(2000), --欲选择字段列表
@TableName VARCHAR(100), --表名或视图表
@Condition1 VARCHAR(3000), --查询条件 where
@Condition2 VARCHAR(1000), --排序表达式 order
@CurrentPage INT = 1, --页号,从0开始
@PageSize INT = 10, --页尺寸
@KeyField varchar(100), --表的主键列
@PageCount int output, --总共可以分多少页
@RecordCount int output, --总的记录数
@sql nvarchar(2000) output --执行的SQL
AS
BEGIN
IF @Fields IS NULL OR LTRIM(RTRIM(@Fields)) = ''
BEGIN
SET @Fields= '*'
END
--最快获取表的部记录数
--select rows from sys.sysindexes where id = object_id('UserInfos') and indid in (0,1)
declare @num numeric(8,2),@pz numeric(8,2),@rpz int
declare @sqltemp nvarchar(3000)
set @sqltemp = 'select @RecordCount=count(*) from '+@TableName+' '+@Condition1
exec sp_executesql @sqltemp,N'@RecordCount int output',@RecordCount output
set @pz = @PageSize
set @num = @RecordCount / @pz
set @rpz = @num
if @num > @rpz set @rpz = @rpz + 1
select @PageCount = @rpz
DECLARE @SqlQuery NVARCHAR(4000)
if @Condition1 is not null and
len(ltrim(rtrim(@Condition2)))>10
Begin
SET @SqlQuery='SELECT '+@Fields+',RowNumber
FROM
(SELECT ' + @Fields+ ',ROW_NUMBER() OVER( '+ @Condition2 +') AS RowNumber
FROM '+@TableName+' '+ @Condition1 +') AS RowNumberTableSource
WHERE RowNumber BETWEEN ' + CAST(((@CurrentPage - 1)* @PageSize+1) AS VARCHAR)
+ ' AND ' +
CAST((@CurrentPage * @PageSize) AS VARCHAR)
+ @Condition2
END
ELSE
Begin
SET @SqlQuery='SELECT '+@Fields+',RowNumber
FROM
(SELECT ' + @Fields+ ',ROW_NUMBER() OVER( order by '+ @KeyField +' desc) AS RowNumber
FROM '+@TableName+' '+ @Condition1 +') AS RowNumberTableSource
WHERE RowNumber BETWEEN ' + CAST(((@CurrentPage - 1)* @PageSize+1) AS VARCHAR)
+ ' AND ' +
CAST((@CurrentPage * @PageSize) AS VARCHAR)
+ @Condition2
END
select @sql=@SqlQuery
SET NOCOUNT ON
EXECUTE sp_executesql @SqlQuery --sp_executesql
SET NOCOUNT OFF
RETURN @@RowCount
END
这里要注意 ,一定要有排序
(SELECT ' + @Fields+ ',ROW_NUMBER() OVER( '+ @Condition2 +') AS RowNumber
没有的话,就按照主键排序吧,这样的话,你后面还有排序的话,结果是会错乱的哟!!!
(SELECT ' + @Fields+ ',ROW_NUMBER() OVER( order by pramarykey desc) AS RowNumber