IF OBJECT_ID('TE_CommonPage','P') IS NOT NULL
DROP PROC [TE_CommonPage]
GO

CREATE PROCEDURE [TE_CommonPage]
@Fieldstr NVARCHAR(255) ='*', -- 查询字段 
@tblName NVARCHAR(255) ='', -- 查询表名 
@Where NVARCHAR(1000) ='', -- 查询条件(不带Where)
@Orderby  Nvarchar(255) ='', -- 查询的排序(Order By **)
@PageSize int = 50,          -- 页尺寸 
@Page int =1,           -- 页码 
@Counts int = 0         ----查询到的记录数

AS 
declare @SQLstr Nvarchar(4000)
declare @OrderbyA Nvarchar(1000)
declare @Temp Nvarchar(1000)
declare @Remainder int --余数
declare @PageCount int --总页数
set @Remainder=0
If @Where<>''
	set @Where = ' Where ' + @Where
if @Orderby<>''
  begin
	set @OrderbyA = ' ' + replace(replace(replace(UPPER(@Orderby),' DESC',' DESC1'),' ASC',' DESC'),' DESC1',' ASC')
	set @Orderby = ' ' + LTrim(@Orderby)
  End
----取得查询结果总数量-----'
If @Counts=0
  begin
	set @Temp = 'select @Counts=Count(*) FROM '+@tblName + @Where
	exec sp_executesql @Temp,N'@Counts int out ',@Counts out
	If @Counts=0
	  set @Counts=1
  end
  
--取得分页总数
set @PageCount=(@Counts+@PageSize-1)/@PageSize
if @Page<1
	set @Page=1
if @Page>@PageCount
   set @Page=@PageCount
set @Remainder=@Counts%@PageSize
if @Remainder=0
	set @Remainder=@PageSize
if @PageCount/2<@Page --后半部分数据处理
	begin
		if @Page=@PageCount --最后一页
			set @SQLstr='Select * from (Select top '+ CAST(@Remainder as VARCHAR(8))+' '+ @Fieldstr+' from ' + @tblName + @Where + @OrderbyA + ') As TempTblA' + @Orderby
		else
			begin
				set @SQLstr='Select Top '+CAST(@PageSize as VARCHAR(8))+ ' * from (Select top '+ CAST(((@PageCount-@Page)*@PageSize+@Remainder) as VARCHAR(8))+' '+ @Fieldstr+' from ' + @tblName + @Where + @OrderbyA + ') As TempTblA' + @Orderby
			end
	end
else --前半部分数据处理
	begin
		if @Page=1 --第一页
			set @SQLstr='Select top '+ CAST(@PageSize as VARCHAR(8))+' '+ @Fieldstr+' from ' + @tblName + @Where + @Orderby
		else
			begin
				set @SQLstr='(Select top '+ CAST(@Page*@PageSize as VARCHAR(8))+' '+ @Fieldstr+' from ' + @tblName + @Where + @Orderby + ') As TempTblB'
				set @SQLstr='(Select Top '+ CAST(@PageSize as VARCHAR(8))+' * From '+@SQLstr + @OrderbyA + ') As TempTblA'
				set @SQLstr='Select * From '+@SQLstr + @Orderby
			end
	end
exec(@SQLstr)-- 执行查询
--print @SQLstr