create proc dbo.msp_Goods
@PageSize int=10,--页面大小
@PageIndex int=1,--当前页码
@PID int,--品牌ID
@isCount bit=1 --记数,0表示计数,1表示提取数据。
as
--关闭计数器
set nocount on
if @isCount= 0
select count(*) from goods where PID =@PID
else begin
--创建临时表
create table #goods
(
id int identity(1,1) primary key,
GID int
)
declare @PageLower int,@PageUpper int
--设置当前页的第一行的行号。
set @PageLower=@PageSize*(@PageIndex-1)+1
--设置当前页的最后一行的行号。
set @PageUpper=@PageSize*@PageIndex
--设置插入的最大行数,可以提高效率。
set rowcount @PageUpper
--向临时表中插入数据。
insert into #goods(GID) select GID from goods where PID=@PID
--提取数据。
select goods.* from goods,#goods
where(goods.GID = #goods.GID)and(#goods.id between @PageLower and @PageUpper)
--删除临时表。
drop table #goods
end
set nocount off
go
execute msp_Goods @PID=10,@isCount=1,@PageIndex=1
execute msp_Goods @PID=10,@isCount=0
支持多排序字段
使用Top,Row_Number比单使用Row_Number应该要高效率一些吧
请看代码~~~
GO
/**//****** 对象: StoredProcedure [dbo].[uspCustomPaging] 脚本日期: 04/03/2007 21:52:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create procedure [dbo].[uspCustomPaging]
@TableName varchar(50), --表或视图名
@Fields varchar(5000) = '*', --字段名(全部字段为*)
@OrderFields varchar(5000), --排序字段(必须!支持多字段,建议建索引)
@SqlWhere varchar(5000) = '', --条件语句(如and Name='a')
@PageSize int, --每页多少条记录
@PageIndex int = 1 , --指定当前为第几页
@TotalPages int output --返回总页数
as
begin
declare @sql nvarchar(4000)
declare @TotalRecords int
--计算总记录数及总页数
set @sql = 'select @TotalRecords = count(*) from ' + @TableName + ' where 1=1 ' + @sqlWhere
exec sp_executesql @sql,N'@totalRecords int output',@TotalRecords output
select @TotalPages=CEILING((@TotalRecords+0.0)/@PageSize)
--处理页数超出范围情况
if @PageIndex<=0
set @PageIndex = 1
if @PageIndex>@TotalPages
set @PageIndex = @TotalPages
set @sql = 'select '+ @Fields + ' from (select top(@PageIndex*@PageSize) ' + @Fields + ',row_number() over(order by ' + @OrderFields + ') as rowNumber from ' + @TableName + ' where 1=1 ' + @SqlWhere + ') t where t.rowNumber >= ((@PageIndex-1)*@PageSize+1)'
--print @Sql
exec sp_executesql @sql,N'@PageIndex int, @PageSize int',@PageIndex,@PageSize
end